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

Managing large constants: `LONG_MAX` vs `LLONG_MAX`

Managing large constants: LONG_MAX vs LLONG_MAX

What you'll learn: How to use header-defined constants to ensure your program handles massive numbers safely across different computer architectures.

The problem with "Big"

In C, the size of a long is a bit of a chameleon. On some systems (like 32-bit Windows or older hardware), a long is 32 bits, topping out at about 2 billion. On others (like 64-bit Linux), it’s 64 bits, reaching quintillions. If you hard-code a maximum value based on your own computer, your code might "overflow" and crash—or behave unpredictably—when compiled elsewhere.

To solve this, the <limits.h> header provides named constants that tell your code exactly what the current system can handle.

Meet the Giants

Think of these constants as the "fences" of your data types. You should use them whenever you need to check if a value is too large to store.

  • LONG_MAX: The largest value a long can hold.
  • LLONG_MAX: The largest value a long long can hold. This is guaranteed to be at least 64 bits (roughly 9 quintillion) on any modern system.

If you are writing a program that calculates national debts or distances between stars, you don't want to guess which "fence" to use. By using these constants, your code becomes "portable," meaning it adapts to the hardware it's running on.

Seeing it in action

Here is how you might use these constants to prevent a calculation from breaking your program:

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

int main() {
    long long user_input = 9223372036854775806LL; // Almost at the limit
    long long added_value = 500;

    // Check if adding these would exceed the maximum allowed value
    if (user_input > LLONG_MAX - added_value) {
        printf("Error: This calculation would exceed LLONG_MAX (%lld)!\n", LLONG_MAX);
    } else {
        long long result = user_input + added_value;
        printf("Result: %lld\n", result);
    }

    printf("For your information, your system's LONG_MAX is: %ld\n", LONG_MAX);
    
    return 0;
}

Why this matters

Using LLONG_MAX instead of a hard-coded number like 9223372036854775807 makes your intent clear to other programmers. It says, "I want the biggest number this type can possibly handle," regardless of whether the computer is a tiny smart-fridge or a massive supercomputer.

Key takeaway

Always use LONG_MAX and LLONG_MAX from <limits.h> to check for overflows and define boundaries for large integer variables.