taeber
Re:A simple defer feature for C
on Monday January 17, 2022 @08:11AM (#29966185)
I'm glad you suggested that, because one of the first comparisons I drew in my article[1] about the "with"-syntax was how it looks like a for-loop.
If you are interested, I did provide a few macros[2], but as another commenter pointed out, they won't handle an early return. You can use "break" to exit early though:
#define with(declare, startup, cleanup, block) \
{ \
declare; \
if (( startup )) { \
do { \
block; \
} while(0); \
cleanup; \
} \
}
with (FILE *fp, fp = fopen(path, "rb"), fclose(fp), {
fread(buf, 1, sizeof(buf)-1, fp);
if (ferror(fp)) {
perror(path);
break;
}
printf("%s\n", buf);
success = 1;
})
There's also "withif" #define withif(declare, startup, cleanup, block, otherwise) \
{ \
declare; \
if (( startup )) { \
do { \
block; \
} while(0); \
cleanup; \
} otherwise; \
}
[1]https://github.com/taeber/cwith
Re:A simple defer feature for C
on Sunday January 16, 2022 @06:31PM (#29961559)
I like the idea of automatic resource cleanup in C and was excited when I read the headline, but I agree with others that the proposed syntax doesn't seem very C-like.
I previously shared a "with" statement idea on HN that I thought fit with the rest of the language.
with (FILE *fp; fp = fopen(path, "wb"); fclose(fp)) {
...
} else {
perror("Failed to open file");
}
https://github.com/taeber/cwithhttps://news.ycombinator.com/item?id=23370693
edit: formatting
Re:Show HN: Automatic cleanup in C using with-statements
on Monday June 01, 2020 @09:30AM (#23378189)
Yes you can. I did mention GCC's cleanup attribute along with MSVC's try-finally construct. Another user was kind enough to even provide an example in their GitHub issue: https://github.com/taeber/cwith/issues/1.
Re:Show HN: Automatic cleanup in C using with-statements
on Monday June 01, 2020 @09:27AM (#23378155)
Thank you! I'd much prefer to not have to use macros, but I tried to make the with/withif mimic what I wish was a real C statement.