首页 > 解决方案 > 预处理器指令(#if 和 #endif)在 C 中不起作用

问题描述

我编写了一个简单的代码来理解 C 中的预处理器指令:

#include <stdio.h>

int main(void)
{
    int a;
    printf("Enter any value : ");
    scanf("%d", &a);
#if a
    printf("The number you entered is non-zero.\n");
    return 0;
#endif
    printf("The number entered is zero.\n");
    return 0;
}

输出如下:

当输入值为零时

Enter any value : 0
The number entered is zero.

当输入的值非零时

Enter any value : 5
The number entered is zero.

作为预处理器#if检查下一个令牌。如果为零,则跳过代码,如果不为零,则正常执行代码。

但是在这两种情况下都跳过了代码。你能解释一下这里有什么问题吗?

标签: cc-preprocessor

解决方案


这个预处理器检查

#if a
...
#endif

在编译时执行,与

int a;

#if a成为true你需要一个先前的声明,例如

#define a 42

#if a成为false你需要一个先前的声明,例如

#define a 0

但是,如果你只是有

#define a

它本身是有效的,但没有定义可测试的值,那么编译器会发出类似的错误

错误 C1017:无效的整数常量表达式

但是拥有#define a 42意味着你不能用它a来定义一个变量,因为

int a;

将扩大到

int 42;

这是一个错误。


推荐阅读