Course contentsShow
← C
Lesson 867 of 1,21912. The Standard LibraryFree lesson

Handling `NAN` and `INFINITY` constants

Handling NAN and INFINITY constants

What you'll learn: How to represent and identify "Not-a-Number" and infinite results in your C programs using constants from the math library.

In regular math classes, we’re taught that dividing by zero is "undefined." In C programming, however, your code needs a way to store these special states without crashing immediately. The <math.h> library provides two special constants for this: NAN and INFINITY.

The Infinite and the Impossible

Think of INFINITY as a value that is larger than any other number. If you divide a positive number by zero, C gives you INFINITY. If you add 1 to INFINITY, you still have INFINITY.

NAN stands for "Not-a-Number." Think of this as the "error" state for math. It happens when you ask for something impossible, like the square root of a negative number or subtracting infinity from infinity. A NAN is like a contagious virus: any math operation involving a NAN will result in another NAN.

Checking for Special Values

You cannot use the standard == operator to check for these values. NAN, by definition, is not equal to anything—not even itself! Instead, C provides two built-in "checker" functions: isnan() and isinf().

#include <stdio.h>
#include <math.h>

int main() {
    double result1 = 1.0 / 0.0;    // Positive Infinity
    double result2 = sqrt(-1.0);   // Not-a-Number (NaN)

    // Checking for Infinity
    if (isinf(result1)) {
        printf("Result 1 is infinite!\n");
    }

    // Checking for NaN
    if (isnan(result2)) {
        printf("Result 2 is not a valid number.\n");
    }

    return 0;
}

Why use them?

Using these constants makes your code "fail-safe." Instead of your program suddenly stopping because it encountered a weird calculation, it can continue running with these placeholders. You can then check your results at the end of a long calculation to see if they are still "real" numbers before printing them to a user or saving them to a database.

Key takeaway

Use isnan() and isinf() to detect mathematical errors or overflows, as standard equality checks (==) will not work on these special constants.