C 宏包含 "incomplete" 三元运算符

C macro contains "incomplete" ternary operator

我正在尝试编译以下内容(在 MSVC 中):

#define TRAP   (errorCode = (errorCode != 0) ? errorCode :) 

int someFunction(int a) {
     printf("Called function with parameter %d\", a);
     return (a > 3);
}

int main(void) {
  int errorCode = 0;
  printf("Error code starts out as %d\n", errorCode);  // errorCode should be 0
  TRAP  someFunction(1);    
  printf("Error code is now %d\n", errorCode);  // errorCode should still be 0
  TRAP  someFunction(4);
  printf("Error code is now %d\n", errorCode);  // errorCode should be 1
  TRAP  someFunction(2);    
  printf("Error code is now %d\n", errorCode);  // errorCode should still be 1, someFunction should not be called.
  return 0;
}

但是,我在包含 "TRAP"

的第一行收到编译器错误
error C2059: syntax error : ')'

我的问题是:为什么?据我了解,宏预处理器只是对 "TRAP" 的所有实例进行查找替换,并将其替换为最外层括号之间的宏文本。因此,在宏完成工作后,我希望第一个 TRAP 行显示为:

errorCode = (errorCode != 0) ? errorCode : someFunction(1);

这是有效的C;确实将这一行直接插入我的代码编译正常。我在这里遗漏了一些宏观的细微差别吗?

如果这是一个愚蠢的问题,我深表歉意 -- 我对宏还很陌生,有点困惑。

它会起作用,但是您将宏的内容括在括号中,因此它会扩展为 (errorCode = (errorCode != 0) ? errorCode :) someFunction(1);

删除宏内容周围的括号,它应该可以工作。

要让 TRAP 以您希望的方式工作,您需要将 TRAP 定义为

#define TRAP   (errorCode = (errorCode != 0) ? errorCode :

即没有尾随 )。然后,您需要在使用宏时提供尾随的右括号,如

TRAP someFunction(1));

有点难看。为了使它看起来有点 "nicer" 你可以参数化定义,如

#define TRAP(func)   (errorCode = (errorCode != 0) ? errorCode : (func))

然后将其调用为

TRAP(someFunction(1));

祝你好运。