可能重复:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?为什么在宏中使用'do {} while(0)'?
在我的C代码,我需要使用宏。我使用gcc编译我的代码。 下面是我的实验:
#define temp(a, b) a++; \
b++;
foo()
{
temp(x, y);
}
^^^^^ this will work fine
#define temp(a, b) a++; \
b++;
foo()
{
if(z)
temp(x, y);
else
foo();
}
^^^^^ this will not work
#define temp(a, b) { \ <<<
a++; \
b++; \
} <<<
foo()
{
if(z)
temp(x, y);
else
foo();
}
^^^^^ this will also not work
#define temp(a, b) do { \ <<<
a++; \
b++; \
} while(0) <<<
foo()
{
if(z)
temp(x, y);
else
foo();
}
^^^^^ this will work :)
顺便说一句,我一般喜欢有功能十岁上下的宏扩展为右值,而不是报表时实际(比如'的#define FOO() (a ++,b ++)'),因为实数函数调用可以包含在rvalues中,但语句不能。 – supercat 2012-06-13 19:38:12