The rule for comparing NaN in C / C ++

Performing some optimizations on a piece of code, the correctness of the code depending on how the handler processes NaNs.

I read the IEEE-754 rules on NaN, which says:

Comparison of EQ, GT, GE, LT, and LE when one or both NaN operands return FALSE.

Comparison of NE, when both or both operands are NaN, returns TRUE.

Are the above rules enforced in C / C ++?

+5
source share
2 answers

C / C ++ does not require a specific floating point representation and does not require any comparison with NaN be false .

In C ++, you can check if all floating point types match IEEE 754 using std::numeric_limits::is_iec559 :

static constexpr bool is_iec559;

56 True if and only if the type adheres to IEC 559. 217

57 Value for all floating point types.


217) The standard of the International Electrotechnical Commission 559 is the same as IEEE 754.

For other floating point comparisons, anti- NaN may or may not behave the same.

In fact, even a representation of NaN not required. See std::numeric_limits<T>::has_quiet_NaN , std::numeric_limits<T>::has_signaling_NaN .

+5
source

The == and != Operators are apparently not limited by the IEEE 754 behavior for NaN s, as indicated by @AlexD's answer.

However, the <math.h> comparison macros must follow the NaN rules equivalent to IEEE 754 . The following draft from C11 draft N1580 in section 7.12.14 Comparison macros state that the <math.h> comparison macros are necessary to ensure that if one or both of x, y are NaN , then:

  • isunordered(x, y) true

  • isgreater(x, y) , isgreaterequal(x, y) , isless(x, y) , islessequal(x, y) all false

Relationship and equality operators support the usual mathematical relationships between numerical values. For any ordered pair of numerical values, exactly one of the relationships - less , greater and equal - is true. Relationship operators may raise an "invalid" floating point exception if the value of the argument is NaN s. For NaN and a numerical value, or for two NaN s, only the disordered ratio is true .

The C++ simply discards in C one on the <math.h> question:

Classification / comparison functions behave in the same way as C macros with the corresponding names defined in 7.12.3, classification macros and 7.12.14, comparison macros in the C standard.

+3
source

All Articles