Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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
like image 244
Reza Afra Avatar asked Sep 09 '18 15:09

Reza Afra


People also ask

What does .0f mean in C?

'f' indicates that you want a float : 0 is an int. 0f is a float.

Is 0.0 a double?

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 .


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.

like image 104
Max Vollmer Avatar answered Oct 27 '22 02:10

Max Vollmer