没有警告将布尔值隐式转换为浮动类型? [英] No warning for implicit cast of bool to floating type?
问题描述
看起来像这样的代码片段即使没有-Weverything也可以在不发出警告的情况下用clang编译:
Looks like this snippet compiles in clang without warning, even with -Weverything:
double x;
...
if (fabs(x > 1.0)) {
...
}
我错过了什么吗?还是编译器和C ++标准认为将 bool
转换为 double
是有意义的事情?
Am I missing something? Or do the compiler and C++ standard think that casting bool
to double
is something that makes sense?
推荐答案
这是使 bool
成为整数类型的结果.根据C ++标准,第3.9.1.6节
This is a consequence of making bool
an integral type. According to C++ standard, section 3.9.1.6
布尔类型的值是
true
或false
(注意:没有signed
,unsigned
,short
或long
bool
类型或值.—尾注) bool类型的值参与积分促销.(重点已添加)
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节中进行了介绍:
This makes values of bool
expressions to be promoted to float
in the same way the int
s are promoted, without a warning, as described in section 4.5.6:
可以将类型为
bool
的prvalue转换为类型为int
的prvalue,其中false
变为零,而true
成为一个.
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
的重载.
EDIT : Starting with C++11 fabs
offers additional overloads for integral types, so the promotion goes directly from bool
to int
, and stops there, because an overload of fabs
is available for it.
这篇关于没有警告将布尔值隐式转换为浮动类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!