I am wondering why compiler doesn't tolerate initializing a float a const long double but allows initialization with a long double literal? Aren't we losing precision in the former?
float f {3.14L}; //compiles
const long double myConst {3.14};
float f{myConst}; // error: non-constant-expression cannot be narrowed from type 'long double' to 'float' in initializer list
'f' indicates that you want a float : 0 is an int. 0f is a float.
A literal 0 is considered to be an int literal; literal 0.0 is a double literal. When assigning to a double , either will work (since the int can be cast in a widening conversion); however, casting 0.0 to an int is a narrowing conversion, and must be done explicitly; i.e. (int)0.0 .
Because in the second example you don't have a constant expression. The compiler tells you that it doesn't allow such a conversion in a non-constant-expression.
The following works:
constexpr const long double myConst{ 3.14 };
float f{ myConst };
On a side note, it seems you are using clang. gcc compiles both your examples, but with a warning in the second case, while MSVC++ raises an error in all cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With