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

c, c-preprocessor

Solution

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.

Problem

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?

Original source

Related problems