If a floating-point value is to be demoted to a floating-point value of a smaller range and precision or to an integer type, or if an integer type is to be converted to a floating-point type, the value must be represented in the new type.
Subclause 6.3.1.4 of the paragraphs 1 and 2 of the C Standard [ISO/IEC 9899:2011] says,
When a finite value of real floating type is converted to an integer type other than
_Bool
, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.When a value of integer type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined.
And subclause 6.3.1.5 paragraph 1 says,
When a value of real floating type is converted to a real floating type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> void func(float f_a) { int i_a; if (f_a > (float) INT_MAX || f_a < (float) INT_MIN) { /* Handle error */ } else { i_a = f_a; } } |
...