2013-08-23 91 views
13

我尝试了一些尴尬的预处理和像这样的东西来到了:预处理器错误时=

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

GCC给我的错误:

test.c: In function ‘main’:
test.c:10:8: error: expected expression before ‘=’ token
test.c:12:8: error: expected expression before ‘=’ token

这是为什么?

+2

可能出现[您遇到过的最糟糕的真实世界宏/预处理器滥用情况?](http://stackoverflow.com/questions/652788/what-is-the-worst-real -world-macros-pre-processor-abuse-youve-ever-come-across)只是在开玩笑,好问题。 –

+1

通过预处理器运行,测试变成'if(x = = 6)'。我不确定为什么这个空间被插入......据推测,知道C规格比我好得多的人会来... – cdhowie

+4

预处理器处理令牌,逻辑上用空格分隔令牌。当它标记'if(x = SIX)'时,它具有'if','(','x','='和'SIX')。当它扩展'SIX'时,它有额外的标记'='和'6',但是两个相邻的标记'='与一个标记'=='不一样(实际上C语法是无效的) - 因此编译错误 –

回答

15

==是一个单一的令牌,它不能被分成两半。你应该在你的代码

从GCC手册页运行gcc -E

-E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output.

Input files that don't require preprocessing are ignored.

为您的代码gcc -E给出了下面的输出

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

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

第二=是什么原因造成的错误信息expected expression before ‘=’ token

5

预处理器不能在字符级别工作,它在t奥肯级。因此,当它进行替换,你得到的东西等价的:

if (x = = 6) 

,而不是你想要的:

if (x==6) 

有一些具体的例外,像#字符串化操作。

+1

'='和'6'之间的空白是从哪里来的? – alk

+1

@alk我只是用空格来显示令牌边界,就C语法而言,'= 6 '和'= 6'。 – Barmar

0

您使用的是什么工具链?如果您使用的是GCC,则可以添加-save-temps选项并检查test.i中间结果以排除您的问题。

我怀疑在x==6之间有一个空格。作为

if (x= =6). 

所以,你得到的错误