Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 236
Gabriel Avatar asked Nov 25 '16 13:11

Gabriel


1 Answers

[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.

like image 164
eerorika Avatar answered Sep 17 '22 15:09

eerorika