浮点除以零不是 constexpr
Floating point division by zero not constexpr
编译时:
constexpr double x {123.0};
constexpr double y = x / 0.0;
std::cout << x << " / 0 = " << y << "\n";
编译器(gcc 4.9.2,-std=c++11 或 c++14)失败,给出错误:
(1.23e+2 / 0.0)' is not a constant expression
constexpr double y = x / 0.0;
在决定 y
是否可以是 constexpr 时,结果 (Inf) 有何相关性?
供参考,这似乎是这样做的方法:
static constexpr double z = std::numeric_limits<double>::quiet_NaN();
static constexpr double w = std::numeric_limits<double>::infinity();
Infinity 是实现定义的结果,标准不需要IEEE floating point and division by zero is formally undefined behavior and constant expression have an exclusion for undefined behavior。
来自 C++ 标准草案部分 5.6
[expr.mul]:
The binary / operator yields the quotient, and the binary % operator
yields the remainder from the division of the first expression by the
second. If the second operand of / or % is zero the behavior is
undefined.
编译时:
constexpr double x {123.0};
constexpr double y = x / 0.0;
std::cout << x << " / 0 = " << y << "\n";
编译器(gcc 4.9.2,-std=c++11 或 c++14)失败,给出错误:
(1.23e+2 / 0.0)' is not a constant expression
constexpr double y = x / 0.0;
在决定 y
是否可以是 constexpr 时,结果 (Inf) 有何相关性?
供参考,这似乎是这样做的方法:
static constexpr double z = std::numeric_limits<double>::quiet_NaN();
static constexpr double w = std::numeric_limits<double>::infinity();
Infinity 是实现定义的结果,标准不需要IEEE floating point and division by zero is formally undefined behavior and constant expression have an exclusion for undefined behavior。
来自 C++ 标准草案部分 5.6
[expr.mul]:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined.