Minimum and maximum values
What you'll learn: How to determine the exact storage limits of different integer types using the limits.h library.
The boundaries of a box
In C, variables are like physical containers. Just as a small cardboard box can only hold a certain amount of weight before it breaks, an integer type can only hold a certain range of numbers before it "overflows."
Because different computers might assign different sizes to an int or a long, you cannot always guess what the largest possible number is. If you try to store the number 5 billion in a container that only holds up to 2 billion, your program won't crash; instead, the number will "wrap around" to a negative value, leading to logic errors that are notoriously hard to find.
Using the limits.h library
To play it safe, C provides a special header file called <limits.h>. This file acts like a cheat sheet for your specific computer, defining constants (labels) that represent the ceiling and the floor for every integer type.
Common constants include:
INT_MAXandINT_MIN: The range of a standardint.SHRT_MAX: The maximum value for ashort.LLONG_MAX: The massive maximum value for along long.
Seeing the limits in action
You can print these values to see exactly how much "room" you have to work with on your current system.
#include <stdio.h>
#include <limits.h>
int main() {
printf("The range of a standard int is: %d to %d\n", INT_MIN, INT_MAX);
printf("The maximum value of a long long is: %lld\n", LLONG_MAX);
// Using an unsigned type? It starts at zero!
printf("The maximum value of an unsigned int is: %u\n", UINT_MAX);
return 0;
}
Why this matters
Imagine you are writing software for a bank to track account balances. Using a standard int might be fine for most people, but if a billionaire joins your bank, their balance might exceed INT_MAX. By checking <limits.h>, you can decide if you need to upgrade to a long long to prevent the balance from accidentally flipping to a negative number.
Key takeaway
Always check limits.h constants when dealing with large datasets to ensure your chosen data type can safely hold your numbers.