<p>NaN as the only value <code>x</code> with the property <code>x!=x</code> is an IEEE 754 guarantee. Whether it is a faithful test to recognize <code>NaN</code> in C boils down to how closely the representation of variables and the operations are mapped to IEEE 754 formats and operations in the compiler(s) you intend to use.</p>

<p>You should in particular worry about “excess precision” and the way compilers deal with it. Excess precision is what happens when the FPU only conveniently supports computations in a wider format than the compiler would like to use for <code>float</code> and <code>double</code> types. In this case computations can be made at the wider precision, and rounded to the type's precision when the compiler feels like it in an unpredictable way.</p>

<p>The C99 standard defined a way to handle this excess precision that preserved the property that only NaN was different from itself, but for a long time after 1999 (and even nowadays when the compiler's authors do not care), in presence of excess precision, <code>x != x</code> could possibly be true for any variable <code>x</code> that contains the finite result of a computation, if the compiler chooses to round the excess-precision result of the computation in-between the evaluation of the first <code>x</code> and the second <code>x</code>.</p>

<p>This <a href="http://arxiv.org/abs/cs/0701192" rel="noreferrer">report</a> describes the dark times of compilers that made no effort to implement C99 (either because it wasn't 1999 yet or because they didn't care enough).</p>

<p>This <a href="https://gcc.gnu.org/ml/gcc-patches/2008-11/msg00105.html" rel="noreferrer">2008 post</a> describes how GCC started to implement the C99 standard for excess precision in 2008. Before that, GCC could provide one with all the surprises described in the aforementioned report.</p>

<p>Of course, if the target platform does not implement IEEE 754 at all, a NaN value may not even exist, or exist and have different properties than specified by IEEE 754. The common cases are a compiler that implements IEEE 754 quite faithfully with FLT_EVAL_METHOD set to 0, 1 or 2 (all of which guarantee that <code>x != x</code> iff <code>x</code> is NaN), or a compiler with a non-standard implementation of excess precision, where <code>x != x</code> is not a reliable test for NaN.</p>
Is `x!=x` a portable way to test for NaN?
<p>In C you can test to see if a double if NaN using <code>isnan(x)</code>.  However many places online, including for example this <a href="https://stackoverflow.com/a/1923933/2179021">SO answer</a> say that you can simply use <code>x!=x</code> instead.</p>

<p>Is <code>x!=x</code> 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.</p>