Using INT_MAX and INT_MIN for overflow checks
What you'll learn: How to use defined constants to prevent your programs from crashing or behaving unpredictably when numbers get too large.
The physical limits of integers
Imagine you have a hand-held tally counter—the kind used to count people entering a building. If the counter only has four digits, the highest number it can show is 9,999. If you click it one more time, it "rolls over" to 0,000.
In C, variables have similar physical limits. Because a standard int uses a fixed amount of memory (usually 32 bits), it cannot hold an infinitely large number. To help us handle these limits, C provides the <limits.h> header, which contains two vital constants: INT_MAX (the largest possible integer) and INT_MIN (the smallest possible negative integer).
Why check before you add?
The danger in C is that the computer won't usually stop you from "rolling over" your tally counter. If you add 1 to a variable that is already at INT_MAX, it will wrap around to a negative number. This is called integer overflow, and it can lead to massive bugs or security holes.
To prevent this, you should check if an operation will exceed the limit before you perform the calculation. You can't just do if (a + b > INT_MAX) because the addition a + b might overflow before the comparison even happens. Instead, you use a bit of "preventative math."
Defensive coding in practice
To check if adding b to a will cause an overflow, you check if a is greater than INT_MAX - b.
#include <stdio.h>
#include <limits.h>
int main() {
int current_score = 2147483640; // Close to INT_MAX
int points_earned = 10;
// Check if adding would exceed the maximum limit
if (current_score > INT_MAX - points_earned) {
printf("Error: Addition would cause overflow!\n");
} else {
current_score += points_earned;
printf("New score: %d\n", current_score);
}
return 0;
}
By subtracting the potential increase from the limit, you create a "safe zone" boundary. If your current value is outside that zone, you know the operation is unsafe. This simple check ensures your program stays within the physical bounds of the hardware.
Key takeaway
Always use INT_MAX and INT_MIN from <limits.h> to validate calculations before they happen to prevent silent data corruption.