【问题标题】:C macro contains "incomplete" ternary operatorC 宏包含“不完整”的三元运算符
【发布时间】:2015-12-18 11:16:11
【问题描述】:

我正在尝试编译以下内容(在 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;确实将这一行直接插入我的代码编译得很好。我在这里遗漏了一些宏观的细微差别吗?

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

【问题讨论】:

  • 顺便说一句,如果您不确定发生了什么,您可以查看宏是如何扩展的。有关 MSVC,请参阅 here
  • @无用。谢谢你让我知道。这个技巧将来肯定会对我有所帮助。

标签: c macros ternary-operator


【解决方案1】:

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

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

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

TRAP someFunction(1));

这有点难看。为了使它看起来更“漂亮”,您可以参数化定义,如

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

然后调用它

TRAP(someFunction(1));

祝你好运。

【讨论】:

    【解决方案2】:

    它可以工作,但您已将宏的内容括在括号中,因此它会扩展为,例如 (errorCode = (errorCode != 0) ? errorCode :) someFunction(1);

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 2016-04-30
      相关资源
      最近更新 更多