C/C++ NaN constant (literal)?
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++.
This can be done using the numeric_limits in C++:
http://www.cplusplus.com/reference/limits/numeric_limits/
These are the methods you probably want to look at:
infinity() T Representation of positive infinity, if available.
quiet_NaN() T Representation of quiet (non-signaling) "Not-a-Number", if available.
signaling_NaN() T Representation of signaling "Not-a-Number", if available.
Is this possible to assign a NaN to a double or float in C ...?
Yes, since C99, (C++11) <math.h>
offers the below functions:
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);
which are like their strtod("NAN(n-char-sequence)",0)
counterparts and NAN
for assignments.
// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
Sample output: (Implementation dependent)
(7ff8000000012345)
(fff000000006789a)
(7ff8000000000000)
... check if the variable is a number or no.
Use isnan(), std::isnan()
from <math.h>, <cmath>
.
As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN()
although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:
Only meaningful if std::numeric_limits::has_quiet_NaN == true.
and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN
it says:
This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.
which as explained here if true
means your platform supports IEEE 754
standard. This previous thread explains this should be true for most situations.