C Programming • C17 baseline, standards-specific features labeled
Integer Promotions, Conversions, and Overflow
Understand usual arithmetic conversions and prevent overflow before performing an operation.
Operands may be promoted or converted before an operation. Signed integer overflow is undefined behavior; unsigned arithmetic wraps modulo one more than the maximum value. Check bounds before addition, multiplication, or narrowing conversions when values may be untrusted.
Example
#include <limits.h>
#include <stdbool.h>
bool add_int(int left, int right, int *result) {
if (result == 0) {
return false;
}
if ((right > 0 && left > INT_MAX - right) ||
(right < 0 && left < INT_MIN - right)) {
return false;
}
*result = left + right;
return true;
}
What to expect
The function writes the sum only when it is representable as int.
Key idea: Check a potentially overflowing operation before evaluating it; checking after overflow is too late.