预处理器#if = = b不支持或错误?

时间:2014-09-23 11:18:12

标签: c c-preprocessor

我正在尝试编译这个小代码。但似乎,我看到了错误的结果。任何想法,我哪里出错了?

int a=2,b=3;
#if a==b
    printf("\nboth are equal.\n");   
#endif

输出:

  两者都是平等的。

1 个答案:

答案 0 :(得分:11)

预处理器在预处理时工作,处理预处理器指令,如#include#define#if-#else-#endif
在编译时之后,像int a=2,b=3;这样的C代码被解析和编译,所以你不应该像这样进行测试。

实际上,当预处理器处理时,符号ab如果您之前没有定义它们,则它们应为空。这就是a==b成立的原因。

EDITED:

以下是一些有效的例子:

int a = 2;
int b = 3;
// To test at runtime
if (a == b)
    puts("They are equal!");

#define A 2
#define B 3

// To test at preprocessing time
#if A==B
// This message is printed at runtime
puts("They are equal!");
#endif

// To test at preprocessing time
#if A==B
// This message is printed at preprocess-time
#error "They are equal!"
#endif