繁体   English   中英

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

[英]Why does the code below return true only for a = 1?

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

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

当Bool true转换为int时,始终将其转换为1。因此,您的代码等效于:

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

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

您的打印语句未执行的原因是因为布尔值被隐式转换为数字,而不是相反。 即您的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";
}

您的布尔值将提升为整数,然后变为1。

在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";
}

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

我建议您切换到一个警告您此事的编译器...(VC ++会产生以下警告:C4806警告:'==':不安全的操作:'bool'类型的值不能提升为'int'类型的值;我手头没有其他编译器。)

我同意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";
}

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM