Question
Why is floating-point zero-divide forbidden in a constexpr?
Using the g++ compiler, both of these compile fine:
constexpr double d1 = 2.0 / 1.0;
const double d2 = 2.0 / 0.0;
But this does not:
constexpr double d2 = 2.0 / 0.0;
The compile-time error is:
error: ‘(2.0e+0 / 0.0)’ is not a constant expression
Note that cppreference gives this exact example, confirming that it's not allowed.
I don't understand why it's not allowed. Keeping in mind that std::numeric_limits::is_iec559 is constexpr
, the compiler clearly knows at compile time, within a constexpr
, whether divide-by-zero is allowed. So, in the case that it is allowed... why isn't it allowed within the constexpr
?
EDIT: It was suggested that this question is siimilar to The behaviour of floating point division by zero . My question here is intended to be more focused (why do the first two expressions appear to be allowed, but the third disallowed)? The answers to the other question don't seem to shed light on that: some of the answers seem to imply all three expressions are UB (and therefore are disallowed? I don't think I believe that; but in any case there's something specific about constexpr that seems to make a difference, thus this question which is focused on the constexpr).
This question is also similar to Compile time floating point division by zero in C++ whose accepted answer (essentially "it's UB so anything goes") doesn't help at all.