Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Reformat

...

Code Block
bgColor#ffcccc
langc
void func(float f_a) {
  int i_a;
 
  /* Undefined if the integral part of f_a >= INT_MAXcannot be represented. */
  i_a = f_a;
}

Compliant Solution (float to int)

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

Code Block
bgColor#ccccff
langc
#include <float.h>
#include <limits.h>
 
void func(float f_a) {
  int i_a;
 
  if (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;
  }
}

...