How to generate NaN, -Infinity and +Infinity in ANSI C? How to generate NaN, -Infinity and +Infinity in ANSI C? c c

How to generate NaN, -Infinity and +Infinity in ANSI C?


There is in C99, but not in previous standards AFAIK.

In C99, you'll have NAN and INFINITY macros.

From "Mathematics <math.h>" (§7.12) section

The macro INFINITY expands to a constant expression of type float representing positive or unsigned infinity, if available; ...

If you're stuck with ANSI C89, you're out of luck. See C-FAQ 14.9.


I don't know if this is standard or portable, but here's a start:

jcomeau@intrepid:/tmp$ cat test.c; make test; ./test#include <stdio.h>int main() { printf("%f\n", 1.0 / 0); printf("%f\n", -1.0 / 0); printf("%f\n", 0.0 / 0); return 0;}cc     test.c   -o testtest.c: In function ‘main’:test.c:3: warning: division by zerotest.c:4: warning: division by zerotest.c:5: warning: division by zeroinf-inf-nan

Strangely enough, I can't get positive NaN using this naive approach.


Also see this: http://www.gnu.org/s/hello/manual/libc/Infinity-and-NaN.html


If you use an old compiler where INFINITY does not exists you can also use the macro HUGE_VAL instead, also defined in the <math.h> library.

HUGE_VAL should be available in C89/C90 standard (ISO/IEC 9899:1990).

References: http://en.cppreference.com/w/c/numeric/math/HUGE_VAL