Step 3 of 7
Signed overflow is undefined
For signed integers, going past INT_MAX is undefined behavior (UB). "Undefined" doesn't mean "wraps around". It means the C standard puts no requirements at all on what happens, and optimizers rely on that. For example, the compiler may delete if (x + 1 < x) entirely, because in a program without UB that condition can never be true.
So you must check before the operation, using only operations that can't overflow:
if (b > 0 && a > INT_MAX - b) /* a + b would overflow upward */
if (b < 0 && a < INT_MIN - b) /* a + b would overflow downward */
(GCC and Clang also offer __builtin_add_overflow, and C23 standardizes ckd_add in <stdckdint.h>. It's still worth knowing how to write the check yourself.)
Your turn: write int checked_add(int a, int b, int *out). If the sum fits, store it in *out and return 1. Otherwise return 0 and leave *out untouched.