Why does compiler accept initialization of a float with a long double literal?

Viewed 205

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
1 Answers

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.

Related