看起来这个片段在 clang 中编译时没有警告,即使使用了 -Weverything:
double x;
...
if (fabs(x > 1.0)) {
...
}
我错过了什么吗?还是编译器和 C++ 标准认为将 bool
转换为 double
是有意义的?
最佳答案
这是使 bool
成为整数类型的结果。根据 C++ 标准,第 3.9.1.6 节
Values of type bool are either
true
orfalse
(Note: There are nosigned
,unsigned
,short
, orlong
bool
types or values. — end note) Values of type bool participate in integral promotions. (emphasis is added)
这使得 bool
表达式的值被提升为 float
,就像提升 int
一样,没有警告,因为在 4.5.6 节中描述:
A prvalue of type
bool
can be converted to a prvalue of typeint
, withfalse
becoming zero andtrue
becoming one.
编辑:从 C++11 开始,fabs
为整数类型提供了额外的重载,因此提升直接从 bool
到 int
,并停在那里,因为 fabs
的重载可用于它。
关于c++ - 没有将 bool 隐式转换为浮点类型的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23874077/