Home > Back-end >  Check for infinity while using -Wfloat-equal?
Check for infinity while using -Wfloat-equal?

Time:12-16

My pet project uses -nostdlib so I can't use any C libraries however I can include them for constants.

Below is my code. If I compile using gcc -Wfloat-equal -nostdlib -O2 -c a.c on gcc or clang it'll give me the error below. I was curious if there's a way to check without triggering this warning. I suspect I can't unless I call code I don't compile

warning: comparing floating-point with ‘==’ or ‘!=’ is unsafe [-Wfloat-equal]

#include <math.h>
int IsInfinity(double d) {
    return d != (double)INFINITY && (float)d == INFINITY;
}

CodePudding user response:

You can use return d < INFINITY && (float) d >= INFINITY;.

Another option is return isfinite(d) && isinf((float) d); if you want to classify negative values symmetrically. (These are macros defined in math.h.)

CodePudding user response:

Code looks like it is trying to test if d is in the finite range and, as a float, is more than FLT_MAX.

// OP's
int IsInfinity(double d) {
  return d != (double)INFINITY && (float)d == INFINITY;
}

if there's a way to check without triggering this warning.

Alternate:

Check via the max values:

int IsInfinity_alt(double d) {
  if (d < 0) d = -d;  // OP can not use fabs().
  return ((float)d > FLT_MAX && d <= DBL_MAX);
}

Had code used the below, some double, just bigger than FLT_MAX function differently than above. It is possible that this behavior is preferred by OP.

return (d > FLT_MAX && d <= DBL_MAX);
  • Related