5

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();
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Wiebe
  • 87
  • 6
  • Related/duplicate: [Why do constant expressions have an exclusion for undefined behavior?](http://stackoverflow.com/q/21319413) – dyp May 26 '15 at 13:28

1 Answers1

5

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.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • `constexpr` is the magic undefined behaviour detector :-) Now we can finally do SFINAE on undefined behaviour. – Kerrek SB May 26 '15 at 13:29
  • @KerrekSB yeah, unfortunately, `gcc` accepts what is formally undefined behavior with shifts in constant expressions, which is kind of a fly in the ointment there. I have a bug report for it but no response yet. – Shafik Yaghmour May 26 '15 at 13:33