Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do while(false) pattern [duplicate]

Tags:

c++

macros

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?

like image 893
sivabudh Avatar asked Jan 12 '11 21:01

sivabudh


People also ask

What is the point of do while false?

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.

What does do while 0 mean in C?

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) {

Do while false in java?

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.


3 Answers

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.

like image 177
Giuseppe Ottaviano Avatar answered Sep 26 '22 00:09

Giuseppe Ottaviano


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.

like image 30
gruszczy Avatar answered Sep 25 '22 00:09

gruszczy


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.

like image 45
Jacob Avatar answered Sep 23 '22 00:09

Jacob