...
This rule does not apply to demotions of floating-point types on implementations that support signed infinity, such as IEEE 754, as all numbers are representable.
Noncompliant Code Example (
...
float
to int
)
This noncompliant code example leads to undefined behavior if the integral part of f_a
cannot be represented as an integer:
Code Block | ||||
---|---|---|---|---|
| ||||
void func(float f_a) {
int i_a;
/* Undefined if the integral part of f_a >= INT_MAX */
i_a = f_a;
} |
Compliant Solution (
...
float
to int
)
This compliant solution assumes that the range of floating-point values of type float
is greater than that of an int
. (This , as is the case in almost all most implementations. ) Unfortunately, there is no safe way to inquire about this assumption in the code short of already knowing the implementation. Converting INT_MAX
to float
is a problem on many implementations, resulting in a power of 2, rather than 1 less.
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;
}
} |
...