Is there any definition how floating-point values evaluated at compile-time are rounded in C or C++ ? F.e. when I have double d = 1.0 / 3.0;
? I.e. what kind of rounding is done at compile-time.
And is there a definition of what's the default-rounding mode for a thread at runtime (C99's / C++11's fegetround()
/ fesetround()
) ?
And is rounding to integer-values also included in the latter configuration parameters ? Im aware of nearbyint()
, but this is specified to bound to the rounding-parameters which can be set by fesetround()
. What I'm concerned about is direct casting to an integer.
In both specs (C17 and C++20), the compile time rounding is implementation defined.
In the C++ spec, this is specified in lex.fcon, which says
If the scaled value is not in the range of representable values for its type, the program is ill-formed. Otherwise, the value of a floating-point-literal is the scaled value if representable, else the larger or smaller representable value nearest the scaled value, chosen in an implementation-defined manner.
The C spec has similar language (quote taken from N2176, C17 final draft):
the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner.
It also recommends that translation time conversion should match execution time conversion by library functions (like strtod
) but it is not required. See the description of representable values.
Conversions of floating point values to integers are specified in both to truncate (round towards 0 by discarding the fractional part).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With