How to produce a NaN float in c?

Using floating point numbers, 0.0 / 0.0 isn’t a “divide by zero” error; it results in NaN.

This C program prints -nan:

#include <stdio.h>

int main()
{
    float x = 0.0 / 0.0;
    printf("%f\n", x);
    return 0;
}

In terms what NaN looks like to the computer, two “invalid” numbers are reserved for “signaling” and “quiet” NaN (similar to the two invalid numbers reserved for positive and negative infinity). The Wikipedia entry has more details about how NaN is represented as an IEE floating point number.

Leave a Comment