为什么true==151被认为是不安全的操作,而true==true ,它实际上持有相同的表达,不是。 此外,为什么true==151永远不会是真的,不像true&&151 ?
cout<<(true==151); //0 and it gives compiler warning C4806 cout<<(true==true); //1 no warning if(true==151)cout<<"1"; //"0" and warning again if(true&&151)cout<<"1"; //1 no warning if(151)cout<<"1"; //1警告C4806本身
'==':不安全的操作:升级为类型'int'的类型'bool'的值不能等于给定的常量
Why is true==151 regarded as unsafe operation while true==true, which is virtually holding the same expression, isn't. Moreover, why can true==151 never be true, unlike true&&151?
cout<<(true==151); //0 and it gives compiler warning C4806 cout<<(true==true); //1 no warning if(true==151)cout<<"1"; //"0" and warning again if(true&&151)cout<<"1"; //1 no warning if(151)cout<<"1"; //1The warning C4806 itself
'==': unsafe operation: no value of type 'bool' promoted to type 'int' can equal the given constant
最满意答案
首先让我们回答第二个问题: true==151总是为false,因为true定义为值1 。
一般情况下,如果你将一个数值解释为一个布尔值,那么0将是错误的,其他的将是真的; 但字面上的true必须具有特定的值,并且该值为1。
那么为什么要警告关于操作数是布尔型和整型的== ? 那么,首先,因为151==true ,如果你注意它,看起来应该是真的(因为151是一个“真实”值),但是 - 如上所述 - 事实并非如此。 这可能是错误的根源,所以值得警告。 更一般地说,你直接比较两种不同的类型,其中隐式转换可能不明显/可能具有非显而易见的后果。
First let's answer your second question: true==151 is always false because true is defined to have the value 1.
In general if you interpret a numeric value as a boolean, 0 will be false and anything else will be true; but the literal true has to have a specific value, and that value is 1.
So why warn about an == where the operands are a bool and an integer? Well, first of all because 151==true, if you eyeball it, looks like it ought to be true (because 151 is a "true" value) but - as noted above - it's not. It's a likely source of error, so that merits a warning. More generally you're directly comparing two different types where the implicit conversion may not be obvious / may have non-obvious consequences.
更多推荐
发布评论