Baum mit Augen
Baum mit Augen

Reputation: 50053

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?

Upvotes: 14

Views: 13947

Answers (3)

SunsetQuest
SunsetQuest

Reputation: 8817

Any comparison(except with "!=") with NaN returns false.

Here is a table I constructed:

     +Dbl_Nan  0_Nan  Inf_Nan  NaN_NaN  +Dbl_Inf  +Dbl_-Inf  Inf_-Inf  Inf_Inf
   -----------------------------------------------------------------------
>  |  False    False  False    False     False     True      True      False
<  |  False    False  False    False     True      False     False     False
== |  False    False  False    False     False     False     False     True
!= |  True     True   True     True      True      True      True      False

Click here for the Rationale on why NaN is always false.

Upvotes: 23

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

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

Upvotes: 18

rici
rici

Reputation: 241701

False.

There is really no such thing as -NaN, although NaN values do carry a sign bit, as well as a payload. But for arithmetic purposes, a NaN is a NaN is a NaN.

Any equality or ordered comparison with a NaN is false.

Upvotes: 1

Related Questions