What is the nan() function in C++?
Overview
The nan() function is used to return a quiet NaN (Not-A-Number) value of type double.
The nan() function is defined in the <cmath> header file.
Syntax
double nan (const char* arg);
Parameter value
The nan() function takes the tagp as its parameter value. tagp represents an implementation-specific-string. When this string is empty (""), the nan() function returns a generic NaN value (the same that is returned by passing NaN to strtod).
Return value
The nan() function returns a quiet NaN value.
Example
#include <iostream>#include <cmath>#include <cstring>using namespace std;int main(){// using the nan() functiondouble var = nan("1");uint64_t dest;// copies variable var to dest// use <cstring> for memcpy()memcpy(&dest, &var, sizeof var);cout << "nan(\"1\") = " << var << " (" << hex << dest << ")\n";return 0;}
Code explanation
- Line 10: We implement the
nan()function to the string value"1"and assign the output to a variablevar. - Line 11: We create another variable
dest. - Line 15: We copy the variable
vartodest. - Line 16: We print our variables.