Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
When one needs to execute multiple statements within preprocessor macro, it’s usually written like
#define X(a) do { f1(a); f2(a); } while(0)
so when this macro is used inside expressions like:
if (...)
X(a);
it would not be messed up.
The question is: wherever I’ve seen such expression, it’s always do { ... } while(0);. Is there any reason to prefer such notion over (in my opinion more clear one) if (1) { ... }? Or am I wrong in my observations and they are equally popular?
Nope, you’re not wrong.
There’s actually a nice reason:
The problem is with the
;! It shouldn’t be there… and that would just look strange and not in the spirit of the language. You can either choose to have a code that expands in to two;in a row, or a code that looks un-c-ish 🙂On the other hand, the
do-whileconstruction does not have that problem.Also, as others mentioned, there’s an
elseproblem:Ignoring the
;issuse, theelseblock now belongs to the wrong if.