In C you can test to see if a double is NaN using isnan(x)
. However many places online, including for example this SO answer say that you can simply use x!=x
instead.
Is x!=x
in any C specification as a method that is guaranteed to test if x is NaN? I can't find it myself and I would like my code to work with different compilers.
Please refer to the normative section Annex F: IEC 60559 floating-point arithmetic of the C standard:
F.1 Introduction
An implementation that defines
__STDC_IEC_559__
shall conform to the specifications in this annex.Implementations that do not define
__STDC_IEC_559__
are not required to conform to these specifications.
F.9.3 Relational operators
The expression
x ≠ x
is true ifx
is aNaN
.The expression
x = x
is false ifX
is aNan
.
F.3 Operators and functions
The
isnan
macro in<math.h>
provides theisnan
function recommended in the Appendix to IEC 60559.