[RFC/PATCH] C++ constexpr vs. floating point exceptions.
Xi Ruoyao
xry111@mengyan1223.wang
Tue Sep 21 13:38:55 GMT 2021
On Tue, 2021-09-21 at 14:15 +0100, Roger Sayle wrote:
>
> Can you double check? Integer division by zero is undefined, but isn't
> floating point
> division by zero defined by the appropriate IEEE standards?
It's an undefined behavior in C++ standard. Even if we assume C++ *was*
IEEE-754 conforming (C++ standard is not saying "C++ is IEEE-754
conforming"!), it would be still not "something can be evaluated in
compile time". IEEE 754 says the default behavior (it can be altered
with some way, for example using feenableexcept() on systems with Glibc)
of floating div-by-zero with both operands finite is "The divideByZero
exception shall be signaled", and:
"The operations of this standard, when exceptional, can as a side effect
raise some of the following status flags: inexact, underflow, overflow,
divideByZero, and invalid operation."
And this is a side effect in real-life: those status flags are normally
implemented as some bits in the floating point status register of the
CPU and can be queried, for example ISO C defined fegetexceptflag() to
do this.
So it's a side effect anyway. You can't evaluate a side-effect during
compilation.
BTW the "correct" way to get a NaN in C++ seems:
#include <limits>
constexpr double my_nan = std::numeric_limits<double>::quiet_NaN();
If the C++ impl supports ISO/IEC 60559 (an alias of IEEE 754), it will
produce a quiet NaN which can be used in constexpr (you can use
signal_NaN() instead of quiet_NaN() if you want a signaling NaN).
Otherwise the compilation will fail.
--
Xi Ruoyao <xry111@mengyan1223.wang>
School of Aerospace Science and Technology, Xidian University
More information about the Gcc-patches
mailing list