为什么所有可能的整数都"true"在 C++ 的 if 语句内的 long int 范围内,而 0 不是?
Why are all possible integers "true" in the range of long int inside if-statement in C++, but 0 is not?
基本上,if语句如何分析整数是真还是假?这两行简单的行打印出"Hello",正整数 764:
int a=764;
if(a){ cout<<"Hello"; }else{ cout<<"Bye"; } //Hello
如果我将整数从正数更改为负数 (-231(,它也会显示"Hello":
int a=-231;
if(a){ cout<<"Hello"; }else{ cout<<"Bye"; } //Hello
但是如果我a
设置为0
,它会变得false
int a=0;
if(a){ cout<<"Hello"; }else{ cout<<"Bye"; } //Bye
它与long int
的范围true
,从-2147483647
到2147483647
,只有一个例外:0
。这是怎么回事呢?if
实际上在做什么来确定这一点?
这是
设计使然的预期行为。C/C++ 中的 if (condition) { ... } else { ... }
语句计算一个布尔表达式,该表达式最终将true
(if
块执行(或false
(else
块执行(。当您将整数作为条件传递时,它必须简化为 true 或 false,并且编译器实际上将其解释为 if (integer != 0)
。对于任何整数类型(有符号或无符号(,这都是相同的。
这是 C/C++ 中非常常见的成语,尽管有人可能会争辩说它不是最清晰的符号,您应该始终明确表示您打算通过使用 if (integer != 0)
来验证整数是否为 0。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 并行用于C++17中数组索引范围内的循环
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 不计算一个范围内的完美数
- 错误:"imread"未在此范围内声明
- 我在范围内未声明的错误类有问题
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- 我有一个数组,我想输入一个范围,然后找到范围内所有偶数的总和?
- 未在此范围内声明错误 'xy'
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 命名空间范围内的外部 - GCC vs clang vs msvc
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 为什么所有可能的整数都"true"在 C++ 的 if 语句内的 long int 范围内,而 0 不是?
- 如何在给定范围内找到 std::set<pair<int、int> > 中的最大值?
- 以下程序中最大 int 1000 000(在 int 范围内)的整数溢出
- C 使用单个生成器从多个范围内提升随机INT
- 检查长类型数据是否在 int 范围内的便携式方法是什么?
- 在检查数字是否在范围内时,无符号int的滚动问题
- 为什么'constexpr const int &a = 1;'在块范围内失败了?