c - 预处理器指令(#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
检查下一个令牌。如果为零,则跳过代码,如果不为零,则正常执行代码。
但是在这两种情况下都跳过了代码。你能解释一下这里有什么问题吗?
解决方案
这个预处理器检查
#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;
这是一个错误。
推荐阅读
- c# - 为什么会编译?分配给只读属性工作正常
- ios - 试图为 UITextfield 宽度约束设置动画,但它不起作用
- python-3.x - 如何在没有round()的情况下获取前5个十进制位置值
- javascript - 在javascript中替换for循环
- javascript - 将 http:// 放在缺少 Angular 协议的 hrefs 上
- php - 当搜索框值与数据库不匹配时如何打开模态
- .net-core - 使用不显眼的 javascript 进行 Div 打印
- c++ - 如何从第二个字符开始传递一个字符串作为函数中的参数进行递归,约束数据类型是函数中的字符串?
- python - 结合 CountVectorizer 和 SelectKBest 会导致标签消失
- python - Python多线程抓取,将数据写入csv文件