定义=时的预处理程序错误

zub*_*rgu 13 c c-preprocessor

我正在尝试一些尴尬的预处理,并得出类似这样的东西:

#include <stdio.h>

#define SIX =6

int main(void)
{
  int x=6;
  int y=2;

  if(x=SIX)
    printf("X == 6\n");
  if(y=SIX)
    printf("Y==6\n");

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

gcc给了我错误:

test.c:在函数'main'中:
test.c:10:8:错误:'='之前的预期表达式
test test.c:12:8:错误:'='之前的预期表达式令牌

这是为什么?

Ant*_*ala 15

==是一个单一的令牌,它不能分成两半.你应该运行gcc -E你的代码

从GCC手册页:

-E在预处理阶段后停止; 不要正确运行编译器.输出采用预处理源代码的形式,发送到标准输出.

忽略不需要预处理的输入文件.

为您的代码gcc -E提供以下输出

  if(x= =6)
    printf("X == 6\n");

  if(y= =6)
    printf("Y==6\n");
Run Code Online (Sandbox Code Playgroud)

第二个=是导致错误消息的原因expected expression before ‘=’ token


Bar*_*mar 5

预处理器不在字符级别工作,它在令牌级别操作.所以当它执行替换时,你得到的东西相当于:

if (x = = 6)
Run Code Online (Sandbox Code Playgroud)

而不是你想要的:

if (x==6)
Run Code Online (Sandbox Code Playgroud)

这有一些特殊的例外,比如#stringification运算符.