Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
Why is the do while(false)
necessary in the macros below?
#define LOG(message, ...) \
do { \
Lock<MutualExclusion> lock (logMutex); \
.... a lot of code ...
} while (false)
I dont think it serves any functional purpose. Am I overlooking something?
The do{}while(false) hides this from the compiler, and is accepted by it as an indication that you really want to do nothing here.
The while(0) loop means that the condition available to us will always be false. The execution of the code will, thus, never really occur. Syntax: while(0) {
while(false) means the condition is false which will end the loop. while(True) means the condition is True which will continue the loop. while (true) is covered by Tamra, while(false) could be used to temporarily skip the while loop when debugging code.
It turns a block into a single statement. If you just use a block (i.e. code enclosed in {}
) strange things can happen, for example
#define STUFF() \ { do_something(); do_something_else(); } if (cond) STUFF(); else //...
the extra semi-colon breaks the syntax. The do {} while(false)
instead is a single statement.
You can find more about this and other macro tricks here.
So you are forced to add semicolon at the end of the macro, when you use it. This is a common idiom and only way to enforce it.
If somebody has code that does this:
if (something)
LOG("My log message");
That would expand to:
if (something)
Lock<MutualExclusion> lock (logMutex);
// A bunch of other code
Which is incorrect (only the first line would be under the if statement).
The macro makes sure that the macro call is inside of a block of code.
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