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

Amir Saniyan picture Amir Saniyan · Jun 4, 2011 · Viewed 30.1k times · Source

I use ANSI C89 (not C++), and I want to generate NaN, -Infinity and +Infinity.

Is there any standard way (eg. standard macro)? Or is there any platform and compiler independent way to generate these numbers?

float f = 0.0 / 0.0; // Is f ALWAYS in any platform is NaN?

Answer

Mat picture Mat · Jun 4, 2011

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.