Danra
Danra

Reputation: 9946

No warning for implicit cast of bool to floating type?

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?

Upvotes: 6

Views: 7163

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

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 true or false (Note: There are no signed, unsigned, short, or long bool types 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 bool can be converted to a prvalue of type int, with false becoming zero and true becoming 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.

Upvotes: 10

Related Questions