编译器警告C4806(number == bool值)的动机是什么?(What is the motivation for Compiler Warning C4806 (number==bool v

编程入门 行业动态 更新时间:2024-10-08 12:45:08
编译器警告C4806(number == bool值)的动机是什么?(What is the motivation for Compiler Warning C4806 (number==bool value)?)

为什么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"; //1

The 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.

更多推荐

本文发布于:2023-04-29 07:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编译器   动机   number   bool   Compiler

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!