C / CHAPTER 03
Integer limits and checked arithmetic
AdvancedCheck whether an operation is representable before evaluating it.
By the end of this chapter
- Separate signed overflow from unsigned wrap
- Use limits from standard headers
- Validate subtraction-based capacity checks
The idea
C integer types have finite ranges, and the language does not promise that int has one universal width. Use limits from limits.h and size information appropriate to the operation. Unsigned arithmetic wraps modulo one more than its maximum value. Signed overflow is undefined behavior, so computing a signed sum and checking afterward is not a reliable overflow detector.
Check the precondition before evaluating the risky operation. For nonnegative signed a and b, a <= INT_MAX - b establishes that a+b fits. For buffer capacities, first ensure used <= capacity, then compare requested <= capacity - used rather than adding sizes that might wrap. Include zero, the exact maximum fitting value, and the first excessive value in tests.
#include <stdio.h>
#include <limits.h>
int add_nonnegative(int a, int b, int *out) {
if (a < 0 || b < 0 || a > INT_MAX - b) return 0;
*out = a + b;
return 1;
}
int main(void) {
int result = 9;
int ok = add_nonnegative(INT_MAX, 1, &result);
printf("%d %d\n", ok, result);
}0 9
The excessive sum is rejected before it is evaluated, and the output remains unchanged.
Try it yourself
Write a capacity check using size_t that rejects inconsistent used/capacity inputs and never evaluates an overflowing sum.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING