Course contentsShow
← C
Lesson 942 of 1,21913. Advanced CFree lesson

Limits of `limits.h` and `stdint.h`

Limits of limits.h and stdint.h

What you'll learn: How to use C’s standard headers to write code that adapts to different hardware capacities without breaking.

The Problem: Shifting Sand

Imagine buying a "medium" shirt. In one store, medium fits a teenager; in another, it fits a bodybuilder. In C, data types like int and long are just like those shirts. On an old 16-bit microcontroller, an int might only hold numbers up to 32,767. On your modern laptop, it likely goes up to 2.1 billion. If you assume an int is always large, your program will crash or behave erratically when moved to smaller hardware.

The Map: limits.h

To write portable code, you shouldn't guess how big a type is. Instead, you consult the "instruction manual" for your specific compiler: <limits.h>. This header defines constants like INT_MAX, CHAR_BIT, and UCHAR_MAX.

Think of these as safety railings. If you are calculating a bank balance, you can check if (balance > LONG_MAX) to prevent an overflow before it happens, regardless of whether a long is 32-bits or 64-bits on that specific machine.

The Blueprint: stdint.h

If limits.h tells you how big your current tools are, <stdint.h> gives you exactly the tool you need. It provides "fixed-width" types. If you absolutely need exactly 32 bits—no more, no less—you use int32_t.

However, portability experts often prefer "minimum-width" types like int_least16_t (at least 16 bits) or "fastest" types like int_fast32_t (the speediest type that holds at least 32 bits). This allows the compiler to pick the "best" fit for the local hardware.

Practical Example

Here is how you use these headers to ensure your code doesn't overflow silently on different systems:

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

int main() {
    // 1. Check the local 'shirt size' for an int
    printf("On this machine, an int maxes out at: %d\n", INT_MAX);

    // 2. Use a guaranteed 64-bit integer for a massive population count
    int64_t global_population = 8000000000; 

    // 3. Prevent overflow by checking against the limit
    int32_t small_total = 2000000000;
    int32_t gain = 2000000000;

    if (gain > INT32_MAX - small_total) {
        printf("Warning: Adding this will exceed 32-bit capacity!\n");
    }

    return 0;
}

Key takeaway

Use limits.h to check the boundaries of standard types and stdint.h to define variables with specific size requirements, ensuring your code runs safely on everything from a toaster to a supercomputer.