Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor changes; reviewed

...

When compiled with GCC 4.8.1 on Linux, this program prints the value -46.

Compliant Solution

This compliant solution replaces the float with a double. Furthermore, it uses an assertion to guarantee that the double type can represent any int without loss of precision for implementations. (See INT35-C. Use correct integer precisions for the definition and rationale of the PRECISION() macro):

Code Block
bgColor#ccccff
langc
#include <assert.h>
#include <stdio.h>
#include <float.h>
#include <limits.h>

extern size_t popcount(uintmax_t);
#define PRECISION(umax_value) popcount(umax_value)  

int main(void) {
  assert(PRECISION(INT_MAX) <= DBL_MANT_DIG * log2(DBL_MANT_DIG));
  int big = 1234567890;
  double approx = big;
  printf("%d\n", (big - (int)approx));
  return 0;
}

On the same platform, this program prints 0.

Risk Assessment

Casting numeric Conversion from integral types to floating-point types can lose informationwithout sufficient precision can lead to loss of precision (loss of least significant bits).

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FLP36-C

Low

Unlikely

Medium

P2

L3

...