CERT-FLP36-C
In this section:
Synopsis
Preserve precision when converting integral values to floating-point type.
Enabled by default
Yes
Severity/Certainty
Low/Low

Full description
Narrower arithmetic types can be cast to wider types without any effect on the magnitude of numeric values. However, whereas integer types represent exact values, floating-point types have limited precision. Conversion from integral types to floating-point types without sufficient precision can lead to loss of precision (loss of least significant bits).
Coding standards
- CERT FLP36-C
Beware of precision loss when converting integral types to floating point
Code examples
The following code example fails the check and will give a warning:
#include <stdio.h>
int main(void) {
long int big = 1234567890L;
float approx = big;
printf("%ld\n", (big - (long int)approx));
return 0;
}
The following code example passes the check and will not give a warning about this issue:
#include <assert.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
extern size_t popcount(uintmax_t); /* See INT35-C */
#define PRECISION(umax_value) popcount(umax_value)
int main(void) {
assert(PRECISION(LONG_MAX) <= DBL_MANT_DIG * log2(FLT_RADIX));
long int big = 1234567890L;
double approx = big;
printf("%ld\n", (big - (long int)approx));
return 0;
}