Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Reverting back to r110 wording for this CS

...

Compliant Solution (float to int)

This compliant solution ensures assumes that the range of values of type type float is  is greater than that of an an int, as is the case in most implementations: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 number one greater than the value of INT_MAX.  Converting INT_MIN to float is a problem on many implementations, resulting in a number one less than the value of INT_MIN.

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

void func(float f_a) {
  int i_a;
 
  if static_assert( 
   (double)INT_MAX < (double)FLT_MAX), 
   "not all int values can be represented as float"
  );
(f_a >= ((float)INT_MAX -1.0) || f_a < ((float)INT_MIN +1.0)|| (f_a >= 0.0F && f_a < FLT_MIN)) {
    /* Handle error */
  } else {
    i_a = f_a;
  }
}

Noncompliant Code Example (Narrowing Conversion)

...