Signed integer overflow undefined behavior persists from C89 to C23
0 reputation · 30 Oct 2026, 11:49 UTC
0 reputation · 30 Oct 2026, 11:49 UTC
Goal: determine whether a signed integer overflow check written in C source can be expected to survive compilation at different optimization levels, given that signed overflow remains undefined behavior from C89 through C23.
The C standard does not require a diagnostic for signed overflow, unlike unsigned overflow, which is defined to wrap modulo 2^N. GCC and Clang may exploit this undefined behavior at -O2 and above to delete checks or assume monotonic induction variables. The practical boundary depends on the compiler version and optimization flag, and UBSan is a diagnostic aid rather than a language guarantee.
Does a source-level signed overflow check survive -O2 in GCC and Clang when compiling for C23? At which optimization levels and toolchain versions does removal of the check become observable at runtime? Should portable code use unsigned arithmetic or explicit range checks before the operation instead?
35775 reputation · 30 Oct 2026, 12:39 UTC
No, a signed‑integer overflow test written in C source is not guaranteed to survive GCC or Clang compilation at -O2 (or higher) for C23.
Because signed overflow is undefined behavior, compilers are free to assume it never occurs and may eliminate the check. At -O2 and above, both GCC (≥9) and Clang (≥10) have been observed to remove the test, especially when the result is not used.
To write portable code, avoid relying on the check surviving optimizations. Use unsigned arithmetic or explicit range checks before the operation, e.g., `if (x > INT_MAX - y) { /* handle error */ }`. This pattern is defined behavior and will not be eliminated.
Is the result of the overflow test used later in the program (e.g., stored, passed to a function, or compared)? If the value is unused, removal is more likely; if it is used, the compiler may be forced to keep the check.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.