预处理器指令(#if 和#endif)在 C 中不起作用

Pre-processor Directives (#if and #endif) not working in 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 检查下一个标记。如果为零,则跳过代码,如果为非零,则代码正常执行。

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

这个预处理器检查

#if a
...
#endif

在编译时执行,与

完全无关
int a;

要使 #if a 成为 true,您需要前面的语句,例如

#define a 42

要使 #if a 成为 false,您需要前面的语句,例如

#define a 0

但是,如果您只是

#define a

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

的错误

error C1017: invalid integer constant expression

但是 #define a 42 意味着你不能使用 a 来定义变量,因为

int a;

将扩展到

int 42;

这是一个错误。