...
When a
double
is demoted tofloat
or along double
is demoted todouble
orfloat
...if the value being converted is outside the range of values that can be represented, the behavior is undefined.
Therefore, implementations that do not allow for the representation of all numbers, conversions of too small of numbers (between zero and FLT_MIN
) may result in undefined behavior.
This rule does not apply to machines floating point implementations that support signed infinity, such as ones that support IEEE - 754, as all numbers are representable.For some non-IEEE-754 machines, conversions of too small numbers (between zero and FLT_MIN
) might produce underflow exceptions that might be considered undefined.
Non-Compliant Code Example
This The following non-compliant code example illustrates possible undefined behavior associated with demoting floating point represented numbersillustrates casts of values that may not be outside of the range of the demoted type.
Code Block | ||
---|---|---|
| ||
long double ld; double d1; double d2; float f1; float f2; /* initializations */ f1 = (float)d1; f2 = (float)ld; d2 = (double)ld; |
As a result of these conversions, it is possible that d1
is outside the range of values that can be represented by a float or that ld
is outside the range of values that can be represented as either a float
or a double
. If this is the case, the result is undefined.
Compliant Solution
This compliant solution properly checks to see whether the values to be stored can be represented in the new type.
...