From 6.3.1.5 of the C99 standard:
If a
double
is demoted to afloat
or along double
is demoted to adouble
or afloat
, ...and the
...
value
...
being converted is outside the range of values that can be represented, the behavior is undefined.
Non-Compliant Code Example
This non-compliant code illustrates possible undefined behavior associated with demoting floating point represented numbers.
...
In the assignments above, it is possible that the variable d1
exceeds the maximum value is outside the range of values that can be stored represented by a float or that the variable ld
exceeds the maximum value is outside the range of values that can be represented as either a float
or a double
.
Compliant Code Example
This compliant code properly checks to see whether the values to be stored are too large to be represented.
Code Block | ||
---|---|---|
| ||
#include <float.h> ... long double ld; double d1; double d2; float f1; float f2; ... if(d1 > FLT_MAX || d1 < -FLT_MAX) { /* Handle error condition */ } else { f1 = (float)d1; } if(ld > FLT_MAX || ld < -FLT_MAX) { /* Handle error condition */ } else { f2 = (float)ld; } if(ld > DBL_MAX || ld > -DBL_MAX) { /* Handle error condition */ } else { d2 = (double)ld; } |
References
Wiki Markup |
---|
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 6.3.1.5, "Real floating types" |