为什么下面的代码仅对a = 1返回true?

时间:2020-03-06 14:52:18  来源:igfitidea点击:

为什么下面的代码仅对a = 1返回true?

main(){
int a = 10;
if (true == a)
     cout<<"Why am I not getting executed";
}

解决方案

因为true为1. 如果要测试a的非零值,只需编写if(a)。

布尔值将提升为整数,然后变为1.

我不希望代码被定义,并且我们不应该依赖于编译器给任何行为。可能是true转换为int(1),而a并未转换为我们期望的bool(true)。最好写出你的意思(a = 0),然后再依赖它(即使事实证明它已经定义了)。

不同于0(为假)的东西不一定为真(即1)

因为布尔值在C / C ++中有点,并且true表示为1,false表示为0。

更新:如评论中所述,我原来的答案是错误的。所以绕开它。

因为true等于1. 它是在pre-procesor伪指令中定义的,所以其中所有带有true的代码在编译之前都会转换为1.

如果将Bool true转换为int,则始终将其转换为1. 因此,代码等效于:

main(){
   int a = 10;
   if (1 == a)
      cout<<"y i am not getting executed";
   }

这是C ++标准的一部分,因此我们希望每一个符合C ++标准的编译器都可以实现这一点。

打印语句未得到执行的原因是,布尔值被隐式转换为数字,而不是相反。 IE。if语句与此等效:if(1 == a)

我们可以通过首先将其显式转换为布尔值来解决此问题:

main(){
int a = 10;
if (((bool)a) == true)
     cout<<"I am definitely getting executed";
}

在C / C ++中,false表示为0。

其他所有内容均表示为非零。有时是1,有时是其他任何东西。
因此,我们永远不要测试是否等于真(==)。

相反,我们应该测试是否存在错误。由于false只有1个有效值。

在这里,我们正在测试所有非假值,它们中的任何一个都可以:

main(){
int a = 10;
if (a)
     cout<<"I am definitely getting executed";
}

第三个例子只是为了证明比较认为是假的任何整数与假(只有0)是安全的:

main(){
int a = 0;
if (0 == false)
     cout<<"I am definitely getting executed";
}

在C和C ++中,0为false,除0外为true:

if ( 0 )
{
// never run
}

if ( 1 )
{
// always run
}

if ( var1 == 1 )
{
// run when var1 is "1"
}

当编译器计算布尔表达式时,它必须产生0或者1. 此外,还有一些方便的typedef和定义,它们使我们可以在表达式中使用" true"和" false"而不是1和0。

因此,代码实际上看起来像这样:

main(){
int a = 10;
if (1 == a)
     cout<<"y i am not getting executed";
}

我们可能想要:

main(){
int a = 10;
if (true == (bool)a)
     cout<<"if you want to explicitly use true/false";
}

或者实际上只是:

main(){
int a = 10;
if ( a )
     cout<<"usual C++ style";
}

我建议我们切换到一个向我们发出警告的编译器...(VC ++会产生以下结果:
警告C4806:'==':操作不安全:提升为'int'类型的'bool'类型的值不能等于给定的常量;我手头没有其他编译器。)

我同意Lou Franco,我们想知道变量是否大于零(或者不等于零),对此进行测试。

如果我们不了解最后一个细节,则编译器隐式完成的所有操作都是危险的。

这是大多数人编写这种代码的方式:

main(){
int a = 10;
if (a) // all non-zero satisfy 'truth'
     cout<<"y i am not getting executed";
}

我也看到了:

main(){
int a = 10;
if (!!a == true) // ! result is guaranteed to be == true or == false
     cout<<"y i am not getting executed";
}