可能重复:
Do-While and if-else statements in C/C++ macros
What’s the use of do while(0) when we define a macro?
我经常看到这样的代码:
#define foo() do { xxx; yyy; zzz; } while (0)
为什么在这里使用包装器?为什么不简单
#define foo() { xxx; yyy; zzz; }
编辑:删除分号。
答案 0 :(得分:3)
这是简单的答案。
#define foo() do { xxx; yyy; zzz; } while (0)
#define foo() { xxx; yyy; zzz; }
if (condition)
foo();
else
x++;
使用do-while版本时,将正确扩展为:
if (condition)
do { xxx; yyy; zzz; } while (0);
else
x++;
当您使用{}版本时,会扩展到此版本,这是语法错误(if
没有匹配else
)。 请注意第二行中的额外分号。
if (condition3)
{ xxx; yyy; zzz; };
else
x++;