问题
Looks like this snippet compiles in clang without warning, even with -Weverything:
double x;
...
if (fabs(x > 1.0)) {
...
}
Am I missing something? Or do the compiler and C++ standard think that casting bool to double is something that makes sense?
回答1:
This is a consequence of making bool an integral type. According to C++ standard, section 3.9.1.6
Values of type bool are either
trueorfalse(Note: There are nosigned,unsigned,short, orlongbooltypes or values. — end note) Values of type bool participate in integral promotions. (emphasis is added)
This makes values of bool expressions to be promoted to float in the same way the ints are promoted, without a warning, as described in section 4.5.6:
A prvalue of type
boolcan be converted to a prvalue of typeint, withfalsebecoming zero andtruebecoming one.
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.
来源:https://stackoverflow.com/questions/23874077/no-warning-for-implicit-cast-of-bool-to-floating-type