Course contentsShow
← C
Lesson 96 of 1,2192. Variables and TypesFree lesson

The `<limits.h>` header file

The <limits.h> header file

What you'll learn: How to use the C standard library to discover the exact capacity of integer types on your specific computer.

The Problem: How big is "Int"?

Imagine you are buying storage bins. One brand says their "Medium" bin holds 10 liters, while another brand's "Medium" bin holds 15 liters. In C, the size of data types like int or long can actually vary depending on the computer or compiler you are using. If you assume an int can hold a value up to 2 billion, but you run your code on an older system where it only goes up to 32,767, your program will crash or behave wildly.

The Solution: A Digital Rulebook

Instead of guessing, we use a special header file called <limits.h>. Think of this file as a built-in encyclopedia that contains the "specifications" for your current machine. It defines a list of constants (names that represent fixed numbers) that tell you the minimum and maximum values for every integer type.

Common constants include:

  • INT_MAX: The largest possible signed int.
  • INT_MIN: The smallest possible signed int.
  • UINT_MAX: The largest possible unsigned int (the minimum is always 0).
  • CHAR_BIT: The number of bits in a single byte (usually 8).

Using the Limits in Code

To see these values, you simply include the header at the top of your file and print the constants using the %d (for signed) or %u (for unsigned) format specifiers.

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

int main() {
    printf("On this computer:\n");
    printf("A signed int can go as low as: %d\n", INT_MIN);
    printf("A signed int can go as high as: %d\n", INT_MAX);
    printf("An unsigned int can reach: %u\n", UINT_MAX);
    
    return 0;
}

Why This Matters

Using <limits.h> makes your code "portable." If you write a program that checks if (my_variable < INT_MAX), that code will work perfectly whether the maximum is 32 thousand or 2 billion. You are letting the computer tell you its own boundaries rather than forcing your own assumptions upon it.

Key takeaway

The <limits.h> header provides pre-defined names for the maximum and minimum capacities of integer types to ensure your code stays safe across different systems.