In many C/C++ macros I’m seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples.
#define FOO(X) do { f(X); g(X); } while (0) #define FOO(X) if (1) { f(X); g(X); } else
I can’t see what the do while is doing. Why not just write this without it?
#define FOO(X) f(X); g(X)
The
do ... whileandif ... elseare there to make it so that a semicolon after your macro always means the same thing. Let’s say you had something like your second macro.Now if you were to use
BAR(X);in anif ... elsestatement, where the bodies of the if statement were not wrapped in curly brackets, you’d get a bad surprise.The above code would expand into
which is syntactically incorrect, as the else is no longer associated with the if. It doesn’t help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.
There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.
The above version of bar
BARexpands the above code into what follows, which is syntactically correct.This doesn’t work if instead of
f(X)you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something likedo ... whileto cause the macro to be a single statement that takes a semicolon without confusion.You don’t have to use
do ... while, you could cook up something withif ... elseas well, although whenif ... elseexpands inside of anif ... elseit leads to a ‘dangling else‘, which could make an existing dangling else problem even harder to find, as in the following code.The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare
BARas an actual function, not a macro.In summary, the
do ... whileis there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they’re worried about.