Compiler Warning C4806 (number==bool value) 的动机是什么?
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本身
'==': unsafe operation: no value of type 'bool' promoted to type 'int' can equal the given constant
首先让我们回答你的第二个问题:true==151
总是错误的,因为 true
被定义为具有值 1
.
一般来说如果您将数值解释为布尔值,0 将为假,其他为真;但文字 true
必须具有特定值,该值是 1.
那么为什么要警告操作数是布尔值和整数的 ==
?好吧,首先是因为 151==true
,如果你观察它,它看起来应该是真的(因为 151 是一个 "true" 值)但是 - 如上所述 - 它不是。这可能是错误的来源,因此值得警告。更一般地说,您直接比较两种不同的类型,其中隐式转换可能不明显/可能有 non-obvious 后果。
为什么 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本身
'==': unsafe operation: no value of type 'bool' promoted to type 'int' can equal the given constant
首先让我们回答你的第二个问题:true==151
总是错误的,因为 true
被定义为具有值 1
.
一般来说如果您将数值解释为布尔值,0 将为假,其他为真;但文字 true
必须具有特定值,该值是 1.
那么为什么要警告操作数是布尔值和整数的 ==
?好吧,首先是因为 151==true
,如果你观察它,它看起来应该是真的(因为 151 是一个 "true" 值)但是 - 如上所述 - 它不是。这可能是错误的来源,因此值得警告。更一般地说,您直接比较两种不同的类型,其中隐式转换可能不明显/可能有 non-obvious 后果。