Why does it only affect floating points?
Some operations on integers are invalid and undefined:
- divide by zero: mathematical operation not defined for the operand
- overflow: mathematical value not representable for the given type
[The compiler will detect such cases on compile time values. At runtime, the behavior is not defined by the standard and can be anything, from throwing a signal, modulo operation, or "random" behavior if the compiler assumed that operations are valid.]
Operations on integers that are valid are completely specified mathematically.
Division of integers in C/C++ (and most programming languages) is an exact operation as it's Euclidean division, not an operation trying to find a close approximation of division of rationals: 5/3
is 1, infinite decimal representation of 5/3 is 1.66... or approximately 1.66666667; closest integer is 2.
The aim of fp is to provide the best approximation of the mathematical operation on "real numbers" (actually rational numbers for the four operations, floats are rational by definition). These operations are rounded according to the curent rounding mode, set with std::fesetround
. So the fp operations are state dependent, the result isn't a function of only the operands. (See std::fegetround, std::fesetround.)
There is no such "state" at compile time, so compile time fp operations cannot be consistent with run time operations, by definition.
constexpr
objects can be treated symbolically, meaning there will be no rounding errors, ie1e100 + 1 - 1e100
will actually be1
as aconstexpr
. – Bindweedconstexpr
? – Gliwice