3 ms·
A cool idea, though the it's in need of some better examples to show its true power. Several of the examples can be accomplished with the traditional C preproce
by breadbox 11y ago
A cool idea, though the it's in need of some better examples to show its true power. Several of the examples can be accomplished with the traditional C preprocessor. For example:
#define with_open_file(fp, path, mode) \
for (FILE *fp = fopen(path, mode) ; fp ; fclose(fp), fp = 0)
- agumonkey 11y agoI don't write C code, isn't this idle code ?
- oso2k 11y agoNo, it's not an infinite loop. If fp comes back as NULL from the initializer part of the loop, then the for loop exits.
- stouset 11y agoAnd if it doesn't come back NULL, it... immediately `fclose`s the pointer and sets it to zero.
- breadbox 11y agoImmediately after executing the loop body, you mean.
- baruch 11y agoUnless someone used continue inside that loop by mistake...
- deleted 11y ago[deleted]
- xamuel 11y agoUsing "continue" in that loop is harmless, it causes the file pointer to be closed and the loop to terminate. Calling "break" is more harmful though, as it would cause the loop to terminate without closing the file, a memory leak.
- breadbox 11y agoNo, it's the head of a for-loop. (The statement or block that follows this macro invocation becomes the body of the loop.) The third clause of the loop head guarantees that the loop can execute at most once.
- agumonkey 11y agoI see, it's partially syntactically correct then, you'll fill in the loop body as if it was the with' one. with_open_file(...) { ... seek(fp,...) read... ... } // nothing remains. I misinterpreted it as some kind of readall | map online, with actual code as 2nd clause of the for loop; reading fp as short for function_pointer at first.
- oso2k 11y agoSaid another way, the for loop can be written as FILE *fp = fopen( path, mode ); while( fp ) { fclose( fp ); fp = 0; } NULL (and 0) evaluate to false in C.
- 72deluxe 11y agoVery interesting, thanks! Do you use many of these macros in your code? Does you find it makes it easier to read? I know some macro substitution can be impossible to read due to the CRAZY_CAPITALNAMES_THEY_GIVE_THEM