Gabriel
Gabriel

Reputation: 9442

float initialization from double with braces

Why does the compiler (clang,gcc) not warn about narrowing conversions when doing this

float a{3.1231231241234123512354123512341235123541235};
float a = {double(3.1231231241234123512354123512341235123541235)}

I expected a warning because I do explicit value-initialization with braces. Following this answer Link it should spit out an error.

Compilation here

Upvotes: 8

Views: 1932

Answers (2)

songyuanyao
songyuanyao

Reputation: 173014

Because the source is a constant expression and overflow does not occur for these cases, then narrowing conversion error won't be triggered.

(emphasis mine)

conversion from a long double to double or to float and conversion from double to float, except where the source is a constant expression and overflow does not occur

If you use it with a double variable(i.e. a non-constant-expression) or a constant with big value which causes overlow, the diagnostic message will be generated. e.g.

double d = 3.14159;
float a {d}; // non-constant-expression cannot be narrowed from type 'double' to 'float' in initializer list

EDIT (for longer input)

Because even if the value cannot be represented exactly by float, overflow still doesn't occur, then it's allowed.

$8.6.4/7.2 List-initialization (emphasie mine)

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

Upvotes: 10

eerorika
eerorika

Reputation: 238441

[dcl.init.list]/§7 (standard draft)

A narrowing conversion is an implicit conversion

...

  • 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

...

Both expressions 3.14159 and double(3.141) are constant expressions and the value is within the range of values representable by float. Therefore the conversion isn't narrowing as defined by the standard and there is no requirement to warn about the conversion.


but it does not give a warning also for longer inputs

Sure it does, as long as the value is outside of the range of values representable by float.

Upvotes: 15

Related Questions