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

Integer ranges in `limits.h`

Integer ranges in limits.h

What you'll learn: How to determine the exact storage capacity of integer types on your specific computer using the limits.h header.

The problem with "Standard" sizes

In C, the size of an integer isn't set in stone. While a char is guaranteed to be one byte, the size of an int or a long can change depending on whether you are programming for a tiny microwave controller or a powerful 64-bit desktop.

If you try to store a number that is too large for its type—like trying to pour a gallon of water into a pint glass—the data will "overflow," leading to unpredictable bugs and negative numbers where you expected positive ones. To write safe code, you need to know exactly where the "rim" of your container is.

Meeting limits.h

The C Standard Library provides a special header file called <limits.h>. Think of this as a reference manual for your specific hardware. It defines a set of constants (macros) that represent the smallest and largest values a variable can hold.

Instead of guessing that an int stops at 2 billion, you can use INT_MAX. Instead of wondering if a char is signed or unsigned by default, you can check CHAR_MIN.

Seeing the limits in action

Here is how you access these constants to see the boundaries of your environment:

#include <stdio.h>
#include <limits.h>

int main() {
    printf("Range of a signed char: %d to %d\n", SCHAR_MIN, SCHAR_MAX);
    printf("Maximum value of an int: %d\n", INT_MAX);
    printf("Maximum value of a long: %ld\n", LONG_MAX);
    printf("Maximum value of an unsigned int: %u\n", UINT_MAX);

    return 0;
}

Why this matters

Using these constants makes your code "portable." If you write a program that checks if (my_total > INT_MAX), that code will work correctly whether the maximum integer is 32,767 (on old 16-bit systems) or 2,147,483,647 (on modern systems). By relying on limits.h rather than hard-coded numbers, your program adapts to the hardware it is running on.

Key takeaway

Use <limits.h> to discover the maximum and minimum capacities of integer types to prevent data overflow and ensure your code works on any machine.