Search code examples
cfloating-pointnan

Is `x!=x` a portable way to test for NaN?


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.


Solution

  • 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 if x is a NaN.

    The expression x = x is false if X is a Nan.

    F.3 Operators and functions

    The isnan macro in <math.h> provides the isnan function recommended in the Appendix to IEC 60559.