Next: , Previous: Varieties of Unportability, Up: Portable C and C++


12.2 Integer Overflow

In C, signed integer overflow leads to undefined behavior. However, many programs and Autoconf tests assume that signed integer overflow after addition, subtraction, or multiplication silently wraps around modulo a power of two, using two's complement arithmetic, so long as you cast the resulting value to an integer type or store it into an integer variable. Such programs are portable to the vast majority of modern platforms. However, signed integer division is not always harmless: for example, on CPUs of the i386 family, dividing INT_MIN by -1 yields a SIGFPE signal which by default terminates the program. Worse, taking the remainder of these two values typically yields the same signal on these CPUs, even though the C standard requires INT_MIN % -1 to yield zero because the expression does not overflow.

GCC users might consider using the -ftrapv option if they are worried about porting their code to the rare platforms where signed integer overflow does not wrap around after addition, subtraction, or multiplication.

Unsigned integer overflow reliably wraps around modulo the word size. This is guaranteed by the C standard and is portable in practice.