为什么编译器接受使用长双精度字面量初始化浮点数?

7

我想知道为什么编译器不允许用const long double来初始化float,但却允许使用long double字面量进行初始化?难道我们在前者中丢失了精度吗?

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
因为编译器知道这个值,并且可以确定它是否适合于浮点数? - Jean-Baptiste Yunès
1
@Jean-BaptisteYunès:如果C++实现使用二进制浮点数,则无法用float表示3.14L的值。 - Eric Postpischil
1个回答

3

因为在第二个示例中,你没有一个常量表达式。编译器告诉你,在非常量表达式中不允许这种转换。

以下代码可以正常运行:

constexpr const long double myConst{ 3.14 };
float f{ myConst };

顺便提一下,看起来你正在使用clang。gcc编译了你的两个示例,但在第二种情况下会有一个警告,而MSVC++在所有情况下都会引发错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接