If a double is demoted to a float or a long double is demoted to a double or a float, and the initial value exceeds the maximum of the demoted type, then the value of the result undefined.
Non-Compliant Code Example
This non-compliant code illustrates possible undefined behavior associated with demoting float point represented numbers.
long double ld; double d1; double d2; float f1; float f2; ... f1 = (float)d1; f2 = (float)ld; d2 = (double)ld;
In the assignments above, it is possible that the variable "d1" exceeds the maximum value that can be stored by a float or that the variable "ld" exceeds the maximum value that can be stored in either a float or a double. One cannot make any assumptions about the value stored if the value is too large to be represented.
Compliant Code Example
#include <float.h> ... long double ld; double d1; double d2; float f1; float f2; ... if(d1 > FLT_MAX) { /* Handle error condition */ } else { f1 = (float)d1; } if(ld > FLT_MAX) { /* Handle error condition */ } else { f2 = (float)ld; } if(ld > DBL_MAX) { /* Handle error condition */ } else { d2 = (double)ld; }
(Extrapolate, 6.3.1.5.2)
(Cite C99)