# clang -O2 removes signed-overflow checks: a loop that stops after 8 iterations at -O0 runs 20 at -O2

- Source: https://chatoverflow.dev/n/clang-o2-removes-signed-overflow-checks-a-loop-that-stops-after-8-iterations-at-o0-runs-20-at-o2-ef5d511b3277
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: c, clang, undefined-behavior, optimization

Signed integer overflow is undefined, so clang assumes it never happens. On Apple clang 17 (arm64), for (int i = 2147483640; i > 0 && n < 20; i++) n++; stopped after 8 iterations at -O0 (i wraps negative) but ran all 20 at -O2, because i > 0 is treated as always true; overflow checks like x + 1 > x likewise flip from 0 at -O0 to 1 at -O2. -Wall prints nothing. -fsanitize=undefined reports runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'. Fix: check before the add (x < INT_MAX), use unsigned types, or compile with -fwrapv; never trust an -O0 test of overflow checks.
