154

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
exebook
  • 32,014
  • 33
  • 141
  • 226
  • Here I show how various NaNs look like when generated by different means: https://stackoverflow.com/questions/18118408/what-is-difference-between-quiet-nan-and-signaling-nan/55648118#55648118 – Ciro Santilli OurBigBook.com Apr 12 '19 at 09:48

5 Answers5

214

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++.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 29
    Or you can compare the number to itself – `x == x` returns `false` iff `x` is NaN. – Archie May 22 '13 at 12:10
  • 8
    @Archie: I don't think that's guaranteed in either language. – Mike Seymour May 22 '13 at 12:13
  • 5
    @MikeSeymour Not by the language standard but as far as I know it _should_ work if the compiler claims to be IEEE compliant. – Pixelchemist May 22 '13 at 12:23
  • 51
    @Pixelchemist: Indeed, it's an option if you need obfuscation but not portability. Personally, I prefer portability without obfuscation, so I won't suggest it myself. – Mike Seymour May 22 '13 at 12:26
  • 11
    minor note: NAN is a float, not a double. [link](http://www.cplusplus.com/reference/cmath/NAN/) – orion elenzil Aug 18 '14 at 21:11
  • 2
    @MikeSeymour `(x == x) == false` is guaranteed in Java, see http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Float.java#Float.isNaN%28float%29 – Oliv Jul 06 '16 at 20:21
  • Thanks for this, I just solved a problem with an external library that just refused to compile properly because it did not understand what NAN meant. – Len Aug 02 '16 at 09:51
  • 1
    `std::numeric_limits::quiet_NaN()` doesn't seem to be a constant in MSVC++2013. – Serge Rogatch Sep 03 '16 at 15:26
  • Does `std::isnan(a)` return true if `a` is `-nan`? – Simon C. Jul 16 '17 at 17:08
  • What about if you can't use `std::numeric_limits`? Is there some other way to get `NaN`, such as a constant defined by dividing zero by zero, or is that a bad idea? – Aaron Franke Nov 07 '19 at 17:56
  • > Or you can compare the number to itself – i have seen bugs from the compiler optimising this out. Always do an explicit check. Hunting this down is such a nightmare that its not worth the zero gain from doing it vs. any robust method. – jheriko Jan 09 '20 at 18:43
  • 2
    Simon, there isn't a `-NaN`. It's just `NaN`. If you evaluate `-NaN` you get `NaN`. There are a bunch of wierd NaNs that no-one uses, and std::isnan() should return true for all of them. Or at least the quiet NaNs, I don't know if it will signal if passed a signalling NaN. – user9876 Dec 22 '21 at 21:44
33

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.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
9

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.
languitar
  • 6,554
  • 2
  • 37
  • 62
  • 8
    +1. Wikipedia has some information on [quiet NaN](http://en.wikipedia.org/wiki/NaN#Quiet_NaN) and [signaling NaN](http://en.wikipedia.org/wiki/NaN#Signaling_NaN). – Drew Noakes Mar 13 '14 at 19:27
7

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>.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 1
    What are the differences between outputs for different strings? Which one should we use in typical numerical code? – quant_dev Jul 26 '20 at 19:55
  • 2
    @quant_dev `x = NAN;` fills most needs, else `x = nan("0x12345");` is a clear way to specify a payload. Payload content differences is implementation defined. Commonly the MSBit of the 52-bit payload is a _quiet_ / _signaling_ flag.. See [NAN](https://en.wikipedia.org/wiki/NaN#Floating_point). – chux - Reinstate Monica Sep 24 '20 at 14:17
  • Great examples, thank you very much. When should we use for example `x = nan("0x12345");` instead of a general `NAN`? I mean why do we need to say `0x12345` is a nan? – afp_2008 Aug 01 '22 at 22:20
  • 1
    @afp_2008 When not-a-number is implemented, there are usually many non-a-numbers. Often quiet and signaling NANs are implemented. When code wants to return something other than the default `NAN`, perhaps to signify quiet/signaling or some other meta data, `nan("some_numeric_string")`. This is a bit of a re-hash of [this](https://stackoverflow.com/questions/16691207/c-c-nan-constant-literal/61902369?noredirect=1#comment113258646_61902369). If you need more, perhaps post a _specific_ question? IIRC, one system tagged with the low bits of address to help facilitate _where_ the NAN originated. – chux - Reinstate Monica Aug 01 '22 at 22:26
  • @chux-ReinstateMonica fyi, the provided link does not work. – afp_2008 Aug 01 '22 at 22:29
  • 1
    @afp_2008 Curious, worked for me to get to my prior comment to quant_dev. – chux - Reinstate Monica Aug 01 '22 at 22:30
-17

yes, by the concept of pointer you can do it like this for an int variable:

int *a;
int b=0;
a=NULL; // or a=&b; for giving the value of b to a
if(a==NULL) 
  printf("NULL");
else
  printf(*a);

it is very simple and straitforward. it worked for me in Arduino IDE.

  • 3
    ```NULL``` and ```NaN``` are actually not the same – Benjamin Zach Sep 28 '20 at 13:18
  • 1
    yes, they are basically different, but using NULL or NaN is same in the sense of checking if the variable is a number or no. – Mohammad Reza Abedini Sep 29 '20 at 09:02
  • 6
    "_it worked for me_" but is not related to the question at all. The question is how to assign `NAN` to a `float` or `double`. This answer does not contain `NAN` or any `float` or `double`. – wovano Sep 20 '21 at 11:17
  • >using NULL or NaN is same in the sense of checking if the variable is a number or no. Not quite - many comparisons with NaN operate differently from this. – rsaxvc Feb 28 '23 at 16:44