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 {} while (0)
and if (1) {} else
are to make sure that the macro is expanded to only 1 instruction. Otherwise:
if (something)
FOO(X);
would expand to:
if (something)
f(X); g(X);
And g(X)
would be executed outside the if
control statement. This is avoided when using do {} while (0)
and if (1) {} else
.
With a GNU statement expression (not a part of standard C), you have a better way than do {} while (0)
and if (1) {} else
to solve this, by simply using ({})
:
#define FOO(X) ({f(X); g(X);})
And this syntax is compatible with return values (note that do {} while (0)
isn't), as in:
return FOO("X");