NaN in C++ with examples

NaN is used for indicating a number that cannot be represented. For example, the square root of negative numbers, zero divided by zero, etc. NaN stands for “Not a Number”. In this tutorial, we will see some examples of nan in C++.

Have a look at this C++ program to understand what is nan.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  int num=-2;
  cout << "sqrt(-2) = " << sqrt(num);
  
  return 0;
}

Output:

sqrt(-2) = nan

As you can see in the example program, we have initialized a variable num with value -2.  Now when we try to find the square root of this number using built-in sqrt() function, we get the result as nan(not a number).

Another example of nan in C++ can be given as the following program. See the below code.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  float num = 0.0;
  cout << "(0.0/0.0) = " << (num/num);
  
  return 0;
}

Output:

(0.0/0.0) = nan

How to check whether a number is NaN or not

We can check whether a number is a nan or not using the following approaches.

  • using isnan()
  • using comparison operator(==)

Method 1: using isnan()

This function returns true if the passed parameter is not a number i.e. a nan value. Have a look at the below-given example code to clear any doubt.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  float num = 0.0;
  float res = num/num;
  
  if (isnan(res))
    {
      cout << "(0.0/0.0) is not a number(nan).\n";
    }
  else
    cout << "(0.0/0.0) is a number.\n";
  
  return 0;
}

The output for the above program is:

(0.0/0.0) is not a number(nan).

Method 2: using “==” operator

There is an interesting property of nan values and that is that they return false when compared to themselves. Which means the following expression will give the result as false.

(nan == nan)

See the following example program to check for a nan value using “==” operator.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  float num = -5;
  float res = sqrt(num);
  
  if (res == res)
    {
      cout << "sqrt(-5) is a number.\n";
    }
  else
    cout << "sqrt(-5) is not a number(nan).\n";
  
  return 0;
}

Output:

sqrt(-5) is not a number(nan).

I hope you understand what is NaN in C++ from this article.

Thank you.

Also read: Swapping two numbers using bitwise operator in C++

Leave a Reply