Integer overflow

In computer programming, an integer overflow occurs when an arithmetic operation on integers attempts to create a numeric value that is outside of the range that can be represented in the space allocated for the result – either higher than the maximum or lower than the minimum representable value.

Most integer arithmetic in modern computation uses binary representation of integers, though decimal representation also exists. This article will focus on binary representation, though similar considerations hold in the other case.

An integer represented as a bit-pattern in a computer can be interpreted as either an unsigned integer (whose value can be from 0 up to some maximum) or a signed integer (whose value can be positive or negative). Most commonly, signed integers are represented in two's complement format, where the high-order bit is interpreted as the sign (0 for +, 1 for −). For example, in a 32-bit word, an unsigned integer has a value from 0 to 232 − 1 = 4,294,967,295, while a signed integer has a value from −231 = −2,147,483,648 to 231 − 1 = 2,147,483,647.

Integer overflow results in a stored value which is different from the mathematical value indicated by the operation which was performed. Most commonly, the resulting bit-pattern is the same as if the operation was performed modulo 2W, where W is the word size in bits. The operation also sets or unsets one or more flags that indicate whether overflow has occurred. On some processors like graphics processing units (GPUs) and digital signal processors (DSPs) which support saturation arithmetic, overflowed results may be clamped, i.e. set to the minimum value in the representable range if the result is below the minimum and set to the maximum value in the representable range if the result is above the maximum.

If it is not anticipated by the programmer, integer overflow can negatively impact a program's reliability and security.