Reputation: 20997
It is well known, if one divides a floating-point number on zero in run-time then the result will be either infinity or not-a-number (the latter case if the dividend was also zero). But is it allowed to divide by zero in C++ constexpr
expressions (in compile time), e.g.
#include <iostream>
int main() {
double x = 0.;
// run-time division: all compilers print "-nan"
std::cout << 0./x << std::endl;
// compile-time division, diverging results
constexpr double y = 0.;
std::cout << 0./y << std::endl;
}
In this program the first printed number is obtained from division in run-time, and all compilers are pretty consistent in printing -nan
. (Side question: why not +nan
?)
But in second case the compilers diverge. MSVC simply stops compilation with the error:
error C2124: divide or mod by zero
GCC still prints -nan
, while Clang changes the sign printing “positive” nan
, demo: https://gcc.godbolt.org/z/eP744er8n
Does the language standard permit all three behaviors of the compilers for compile-time division: 1) reject the program, 2) produce the same division result as in run-time, 3) produce a different (in sign bit) result?
Upvotes: 2
Views: 373
Reputation: 12849
Division by zero is undefined behavior. (So anything goes)
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf Section 8.5.5, point 4
Upvotes: 2