Possible Duplicates:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
do { … } while (0) what is it good for?
I’m working on some C code filled with macros like this:
#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0)
Can anyone explain what this macro does, and why do {} while(0) is needed? Wouldn’t that just execute the code once?
is doing the exact same thing as stuff(). So what’s the big deal, then? The issue is with the syntax of macros. Suppose we defined the macro like:
Then, there are two issue. The first is relatively minor: uses of SAFE_FREE no longer require a trailing semi-colon. More importantly, though, code like:
Will expand to:
Note, how the
elsenow matches the wrongifstatement. This completely alters the program-flow, even though it does not look like that in the source code.Defining the macro as above prevents weird behavior as above, since
do { ... } while(0)acts just like a statement without its semicolon.