...
In this noncompliant example, an int
is converted to float
.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> int main() { int big = 1234567890; float approx = big; printf("%d\n", (big - (int)approx)); return 0; } |
...
This solution replaces the float
with a double
. Furthermore, it uses a static assertion to guarantee that the double
type can represent any int
without loss of precision. (See recommendation DCL03-C. Use a static assertion to test the value of a constant expression.)
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> #include <float.h> /* define or include a definition of static_assert */ static_assert(sizeof(int) * 8 <= DBL_MANT_DIG); // 8 = bits / char int main() { int big = 1234567890; double approx = big; printf("%d\n", (big - (int)approx)); return 0; } |
...