Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point division by zero not constexpr

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();
like image 779
Wiebe Avatar asked May 26 '15 13:05

Wiebe


1 Answers

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.

like image 169
Shafik Yaghmour Avatar answered Nov 06 '22 06:11

Shafik Yaghmour