Technical article 100826

Comparing NaN with any other float value results in a 'true' response.

OpenServer 5.0.0OpenServer 5.0.2

Written · Last revised

Problem

The C compiler results in a 'true' response on comparison of a
NaN with an arbitrary float value.  The following example code
shows the current behavior of cc(1):
#include <ieeefp.h>
#include <stdio.h>
main()
{
    float f;

/* make f a NaN */ *(long *)&f=0xffc00000L; fpsetmask(FP_X_DZ);

printf("f: %f\n", f);

if ( f == 1.0 ) printf("Comparison f == 1.0 is true\n"); else printf("Comparison f == 1.0 is false\n");

}

The output of the above program is:

$ a.out
f: -nan
Comparison f == 1.0 is true

Cause

Although this is outside the spec of ANSI C, the IEEE and other bodies recommend the result of such a comparison to be 'false'. SCO engineering is currently improving the C compilation system to meet these recommendations. These improvements will be included in a future release of the product.

Solution

If you need to compare floating point values and are not sure if a floating point variable is infinity or NaN, then use the isnan() macro prior to the comparison, as in the example below.

#include <ieeefp.h>
#include <stdio.h>
main()
{
    float f;

/* make f a NaN */ *(long *)&f=0xffc00000L; fpsetmask(FP_X_DZ);

printf("f: %f\n", f);
if ( !isnan(f) && f == 1.0 )
    printf("Comparison f == 1.0 is true\n");
else
    printf("Comparison f == 1.0 is false\n");
}

See also

cc(1), cc(CP), isnan(S), ieee_functions(3BSD), fpgetround(3C),
fpgetround(S)

From the Xinuos technical article database, record 100826. Reproduced with permission. The original is at www.sco.com/ta/100826, which is reachable but blocked from search engines. Xinuos marks this article against a retired product line. That refers to the product’s lifecycle, not to whether the advice still works — plenty of it still applies to running systems.

Next step

Need this fixed rather than explained?

Tell us the release, what the system runs and what it is doing. We will reply by email with what we would do next.

  • You deal with the people who do the work
  • No obligation, and no upgrade required before we will help
  • We tell you plainly if something is not worth doing

Send an enquiry

We reply by email. If a server is down, say so in the first line. You can also write to help@scoexpert.com.