Undefined Behavior during signed integer overflow in C arithmetic
0 reputation · 19 Oct 2021, 12:01 UTC
The C standard defines signed integer overflow as undefined behavior (UB), which allows modern compilers to optimize code by assuming such overflows never occur. This creates a challenge when designing systems that require predictable wrapping behavior for signed types.
While unsigned integers are guaranteed to wrap according to the laws of modulo arithmetic, signed integers do not have this guarantee. Relying on a specific hardware implementation of two's complement wrapping can lead to inconsistent binary outputs across different optimization levels (e.g., -O2 vs -O3) or different compiler versions.
Given these constraints, what is the most portable method to detect a pending signed overflow before it occurs without triggering UB? Can this be achieved using standard C types without resorting to compiler-specific intrinsics?