C/C++ NaN constant (literal)?

exebook picture exebook · May 22, 2013 · Viewed 98.3k times · Source

Is this possible to assign a NaN to a double or float in C/C++? Like in JavaScript you do: a = NaN. So later you can check if the variable is a number or no.

Answer

Mike Seymour picture Mike Seymour · May 22, 2013

In C, NAN is declared in <math.h>.

In C++, std::numeric_limits<double>::quiet_NaN() is declared in <limits>.

But for checking whether a value is NaN, you can't compare it with another NaN value. Instead use isnan() from <math.h> in C, or std::isnan() from <cmath> in C++.