为什么所有可能的整数都"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?

本文关键字:范围内 int long 不是 if 整数 有可能 true 为什么 C++ 语句      更新时间:2023-10-16

基本上,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,从-21474836472147483647,只有一个例外:0。这是怎么回事呢?if实际上在做什么来确定这一点?

这是

设计使然的预期行为。C/C++ 中的 if (condition) { ... } else { ... } 语句计算一个布尔表达式,该表达式最终将true(if块执行(或false(else块执行(。当您将整数作为条件传递时,它必须简化为 true 或 false,并且编译器实际上将其解释为 if (integer != 0) 。对于任何整数类型(有符号或无符号(,这都是相同的。

这是 C/C++ 中非常常见的成语,尽管有人可能会争辩说它不是最清晰的符号,您应该始终明确表示您打算通过使用 if (integer != 0) 来验证整数是否为 0。