In many C/C++ macros I\'m seeing the code of the macro wrapped in what seems like a meaningless do while
loop. Here are examples.
#define FOO(X
Jens Gustedt's P99 preprocessor library (yes, the fact that such a thing exists blew my mind too!) improves on the if(1) { ... } else
construct in a small but significant way by defining the following:
#define P99_NOP ((void)0)
#define P99_PREFER(...) if (1) { __VA_ARGS__ } else
#define P99_BLOCK(...) P99_PREFER(__VA_ARGS__) P99_NOP
The rationale for this is that, unlike the do { ... } while(0)
construct, break
and continue
still work inside the given block, but the ((void)0)
creates a syntax error if the semicolon is omitted after the macro call, which would otherwise skip the next block. (There isn't actually a "dangling else" problem here, since the else
binds to the nearest if
, which is the one in the macro.)
If you are interested in the sorts of things that can be done more-or-less safely with the C preprocessor, check out that library.