【问题标题】:Grouping in C macros [duplicate]C宏中的分组[重复]
【发布时间】:2012-11-30 13:11:03
【问题描述】:

可能重复:
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)

为什么在这里使用 do-while 包装器?为什么不简单

#define foo() { xxx; yyy; zzz; }

?

编辑:删除分号。

【问题讨论】:

  • 我打赌你宁愿看到#define foo() do { xxx; yyy; zzz; } while (0)(没有尾随分号 - 这正是为什么......)
  • 在 SO 搜索栏中搜索 [c]while (0),你会得到很多答案。
  • 其他帖子的链接确实回答了这个问题:gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html
  • @Lundin - 在其他帖子上查看用户:raghava 的答案(链接)。
  • @Lundin 接受答案的第四个代码块解决了问题的这一部分。

标签: c


【解决方案1】:

这是简单的答案。

#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++;

当您使用 {} 版本时,它会扩展到此,这是一个语法错误(与 else 不匹配的 if)。 注意第二行中多余的分号。

if (condition3)
    { xxx; yyy; zzz; };
else
    x++;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2015-01-15
    • 2018-10-14
    • 2016-02-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多