Search code examples
c++floating-pointnanieee-754

What is the result of comparing a number with NaN?


Consider for example

bool fun (double a, double b) {
    return a < b;
}

What will fun return if any of the arguments are NaN? Is this undefined / implementation defined behavior?

What happens with the other relational operators and the equality operators?


Solution

  • The C++ standard merely says:

    [expr.rel]/5 If both operands (after conversions) are of arithmetic or enumeration type, each of the operators shall yield true if the specified relationship is true and false if it is false.

    So basically, a < b is true if a is less than b.

    However, the implementation may claim conformance to IEC 559 aka IEEE 754 standard for floating point arithmetic, via numeric_limits::is_iec559. Then it is governed by that standard in section 5.7 and table 4, which requires that all comparisons but != involving NaN report false. != involving NaN reports true