#define中的C++ void cast和operator逗号

Gio*_*hal 15 c++ macros

我在阅读一些源代码时发现了这一点.

 #define MACRO(x)  if((void) 0, (x)); else some_func();
Run Code Online (Sandbox Code Playgroud)

我不完全理解操作符逗号和void转换背后的原因.这可能与宏保护有关,我知道(void)0有时用来保护else宏中的级联,例如in if(...) then foo(); else (void)0.

为什么运算符逗号有什么想法?

编辑:我开始认为这与猫头鹰有关 (0,0).

AnT*_*AnT 8

我猜这个技巧用于防止用户在if条件中声明变量.您可能知道,在C++中,这样做是合法的

if (int i = some_func()) {
   // you can use `i` here
}
else  {
   // and you can use `i` here
}
Run Code Online (Sandbox Code Playgroud)

在该定义中使用逗号运算符将阻止宏的使用,如

MACRO(int i = some_func());
Run Code Online (Sandbox Code Playgroud)

并强制用户仅使用表达式作为参数.