Floating point division by zero not constexpr

邮差的信 提交于 2019-12-12 11:51:56

问题


When compiling this:

constexpr double x {123.0};
constexpr double y = x / 0.0;
std::cout << x << " / 0 = " << y << "\n";

The compiler (gcc 4.9.2, -std=c++11 or c++14) fails, giving error:

(1.23e+2 / 0.0)' is not a constant expression
  constexpr double y = x / 0.0;

How is the result (Inf) relevant when deciding if y can be a constexpr or not?

For reference, this seems to be the way to do it:

static constexpr double z = std::numeric_limits<double>::quiet_NaN();
static constexpr double w = std::numeric_limits<double>::infinity();

回答1:


Infinity is an implementation defined result, the standard does not require IEEE floating point and division by zero is formally undefined behavior and constant expression have an exclusion for undefined behavior.

From the draft C++ standard section 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.



来源:https://stackoverflow.com/questions/30459773/floating-point-division-by-zero-not-constexpr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!