Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
Danra Avatar asked May 26 '14 16:05

Danra


People also ask

How do you avoid implicit conversions?

Using explicit constructors and conversion operators to avoid implicit conversion. Before C++11, a constructor with a single parameter was considered a converting constructor. With C++11, every constructor without the explicit specifier is considered a converting constructor.

What is implicit type conversion in C++?

The implicit type conversion is the type of conversion done automatically by the compiler without any human effort. It means an implicit conversion automatically converts one data type into another type based on some predefined rules of the C++ compiler. Hence, it is also known as the automatic type conversion.

What happens in implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.


1 Answers

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.

like image 100
Sergey Kalinichenko Avatar answered Sep 28 '22 11:09

Sergey Kalinichenko