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?
You may see a do loop with the conditional expression set to a constant value of zero (0). This creates a loop that will execute exactly one time. This is a coding idiom that allows a multi-line macro to be used anywhere that a single statement can be used.
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
A Do… While loop is used when we want to repeat a set of statements as long as the condition is true. The condition may be checked at the beginning of the loop or at the end of the loop.
Importance of macros in C++ 99.9% of the C++ programs use macros. Unless you are making a basic file you have to write #include, which is a macro that pastes the text contained in a file.
Nope, you're not wrong.
There's actually a nice reason:
#define my_code if (1) { ... }
if (1)
my_code;
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-while
construction does not have that problem.
Also, as others mentioned, there's an else
problem:
if (1)
my_code;
else { ... }
Ignoring the ;
issuse, the else
block now belongs to the wrong if.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With