Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example leads to undefined behavior if the integral part of f1 cannot be represented as an integer.

Code Block
bgColor#ffcccc
langc
float f1;
int i1;

/* initialize fl */

i1 = f1; /* Undefined if the integral part of f1 > INT_MAX */

...

This compliant solution assumes that the range of floating-point values is greater than that of an int. (This is the case in almost all implementations.) Unfortunately, there is no safe way to inquire about this assumption in the code short of already knowing the implementation.

Code Block
bgColor#ccccff
langc
float f1;
int i1;

/* initialize fl */

if (f1 > (float) INT_MAX || f1 < (float) INT_MIN) {
  /* Handle error */
} else {
  i1 = f1;
}

...

This noncompliant code example contains conversions that may be outside of the range of the demoted types.

Code Block
bgColor#FFCCCC
langc
long double ld;
double d1;
double d2;
float f1;
float f2;

/* initializations */

f1 = (float)d1;
f2 = (float)ld;
d2 = (double)ld;

...

This compliant solution checks to see whether the values to be stored can be represented in the new type.

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

long double ld;
double d1;
double d2;
float f1;
float f2;

/* initializations */

if (d1 > FLT_MAX || d1 < -FLT_MAX) {
  /* Handle error condition */
} else {
  f1 = (float)d1;
}
if (ld > FLT_MAX || ld < -FLT_MAX) {
  /* Handle error condition */
} else {
  f2 = (float)ld;
}
if (ld > DBL_MAX || ld < -DBL_MAX) {
  /* Handle error condition */
} else {
  d2 = (double)ld;
}

...