In C++, std::isnan(x) checks whether a value is NaN, which stands for "not a number". NaN is what you get from calculations with no real answer, such as std::sqrt(-1.0), 0.0 / 0.0, or infinity - infinity.
NaN is strange: it is not equal to anything, not even to itself. So x == NaN never works, and isnan(x) is the right way to test. It is also a good way to print a friendly message instead of the confusing text nan or -nan.
std::isnan() is declared in <cmath> and is part of the group Classification and comparison. These tools ask what kind of number you have: normal, zero, infinite, or NaN. In C++ they are ordinary overloaded functions in std, not macros.
Syntax
Include <cmath> and call std::isnan. Start with these lines.
C++
bool a = std::isnan(1.5); // false
bool b = std::isnan(std::sqrt(-1.0)); // true
bool c = std::isnan(std::nan("")); // true
Call
What it does
std::isnan(1.5)
An ordinary number. Returns false.
std::isnan(std::sqrt(-1.0))
The square root of a negative number is NaN. Returns true.
std::isnan(std::nan(""))
A NaN made on purpose. Returns true.
Write std:: in front, and include <cmath>. The function returns a bool, so use std::boolalpha to print true or false.
The variable x holds a NaN, so the three lines test the same value in different ways.
The test x == x is false, even though it is the same variable. NaN is not equal to anything, including itself. That is why x != x is true.
The trick x != x works, but std::isnan(x) says the same thing clearly, so it is the one to use.
Example 3 — Print a Message Instead of NaN
Take the square root of several numbers. If the answer is NaN, print a clear message instead.
C++
#include <cmath>
#include <iostream>
int main() {
double inputs[] = {16.0, -4.0, 25.0};
for (double x : inputs) {
double r = std::sqrt(x);
if (std::isnan(r)) {
std::cout << "sqrt(" << x << ") is not a real number\n";
} else {
std::cout << "sqrt(" << x << ") = " << r << '\n';
}
}
return 0;
}
Output
sqrt(16) = 4
sqrt(-4) is not a real number
sqrt(25) = 5
How It Works
The loop calculates the square root first and checks the answer with isnan() before printing.
sqrt(16) and sqrt(25) are real numbers (4 and 5), so the else branch prints them.
sqrt(-4) has no real answer, so it returns NaN. The if branch runs and the user sees a clear message instead of -nan.
Frequently Asked Questions
std::isnan(x) returns true if x is NaN (not a number), and false for every other value, including infinity.
true if x is NaN, otherwise false. Infinity and zero return false.
NaN is not equal to any value, including another NaN. Every comparison with it gives false, except !=. Use std::isnan(x) instead.
No. Infinity is a valid special value, so isnan(inf) is false. Use std::isinf() for infinity, or std::isfinite() to rule out both.
Include <cmath> and write std::isnan(). That always works and picks the C++ overloads. The global name ::isnan often works too, but the standard does not promise it, and it may only take a double.