Using the {}
initializer in C++11
to initialize bool b = {2}
yields the following warning message:
warning: narrowing conversion of ‘2’ from ‘int’ to ‘bool’ inside { } [-Wnarrowing]
However, using the old style bool b = 2
has no such problem. What is the reason behind this?
Update: I compiled the code using g++ -std=c++11
and it gave me the warning. If I add the option -pedantic-errors
, the warning becomes an error.
Narrowing a data type in an initialization-list makes your c++11 program ill formed, in this situation the compiler can either give a warning or keep going.
Interestingly enough you can actually change it to bool b = {1}
and there is no warning, I'm assuming because the value of a bool is guaranteed to convert to 0 and 1 in integral types.
Here is a standard quote confirming the error.
A narrowing conversion is an implicit conversion
— from a floating-point type to an integer type, or
— from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or
— from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or
— from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.
As indicated above, such conversions are not allowed at the top level in list-initializations