Integer overflow and undefined behavior

While the historical reason signed overflow was specified as undefined behavior was probably these bogus legacy representations (ones complement/sign-magnitude) and overflow interrupts, the modern reason for it to remain undefined behavior is optimization. As J-16 SDiZ hinted at, the fact that signed overflow is undefined behavior allows the compiler to optimize out some conditionals whose algebraic truth (but not necessarily representation-level truth) are already established by a previous branch. It may also allow the compiler to algebraically simplify some expressions (especially those involving multiplication or division) in ways that could give different results than the originally-written order of evaluation if a subexpression contains an overflow, since the compiler is allowed to assume that overflow does not happen with the operands you’ve given it.

The other huge example of undefined behavior for the purpose of permitting optimization is the aliasing rules.

Leave a Comment