Signed integer overflow check optimized away in C
0 reputation · 19 Jul 2022, 02:30 UTC
Signed integer overflow guard disappears after optimization
ISO C defines signed integer overflow as undefined behavior. A compiler may assume the overflow never occurs and remove an explicit overflow check, even when the source appears to guard against it. I need to know whether a bounds check written for signed arithmetic can be relied upon across common C toolchains.
The uncertainty centers on optimization level, compiler version, and language standard from C99 through C23. Unsigned overflow is defined to wrap modulo 2 to the power of N, but signed overflow has no required errno, diagnostic, or trap. I am looking for a portable way to express the intent without depending on wraparound semantics, and per-toolchain verification would be needed before deployment.
- Does ISO C permit a compiler to delete a signed overflow check that is provably unreachable only because overflow is undefined?
- Which compiler flags or language-standard selections affect whether the check survives?
- Is there a standards-conforming C idiom for detecting signed overflow before it occurs?