Narrower primitive types can be cast to wider types without any effect on the magnitude of numeric values. However, whereas integers represent exact values, floating-point numbers have limited precision. C99 says, in Section 6.3.1.4 : "Real floating and integer"of the C standard [ISO/IEC 9899:2011] states:
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.
...
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;
}
|
...
The CERT Oracle Secure Coding Standard for Java: NUM13-J. Avoid loss of precision when converting primitive integers to floating-point
ISO/IEC 9899:19992011 6.3.1.4: "Real floating and integer"
...