Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do { } while(0) vs. if (1) { } in macros [duplicate]

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?

like image 664
aland Avatar asked May 23 '12 13:05

aland


People also ask

Do while Do 0 macros?

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.

Why macros use do while?

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.

Do while in macro definition?

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.

Should macros be used in C++?

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.


1 Answers

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.

like image 185
penelope Avatar answered Oct 04 '22 20:10

penelope