Macro scope guards [duplicate]
Possible Duplicates:
Why are there sometimes meaningless do/while and if/else statements in C开发者_Python百科/C++ macros? What's the use of do while(0) when we define a macro?
Is there a difference between
#define MACRO(x) \
{ \
... \
}
and
#define MACRO(x) \
do { \
... \
} while(0)
?
do { ... } while(0) allows the macro to be used in conditional code.
Looks like this question has been asked before: C multi-line macro: do/while(0) vs scope block
Here's another link to a couple of reasons to do so, and why to omit the semicolon at the end.
Well, the second feels more natural since it always requires a semicolon after using it.
EDIT RE-EDITED
in literature I can remember always the form do {..} while(0)
(sometimes even with the ;, but this form proved to be wrong). Since macros are literal substitution, it is easy to imagine that there's a difference when { }
is allowed but do { } while(0)
is not, or when you need the MACRO behaves like a "statement" ({ };
do not, while do { } while(0);
does; an example is the case of if / else( if):
if (COND)
{ // MACRO(..);
...
};
else
{ // this is an else without if
}
while
if (COND)
do { // MACRO(..);
...
} while(0);
else
{
// this work properly
}
So the first has a void statement that syntactically makes impossible to "join" the else to its if, while the second form is correct (and if the macro has the final ; as I remembered to have seen somewhere, the same error of the first form occurs)
精彩评论