Overflow flag


In computer processors, the overflow flag is usually a single bit in a system status register used to indicate when an arithmetic overflow has occurred in an operation, indicating that the signed two's-complement result would not fit in the number of bits used for the operation. Some architectures may be configured to automatically generate an exception on an operation resulting in overflow.
An illustrative example is what happens if we add 127 and 127 using 8-bit registers. 127+127 is 254, but using 8-bit arithmetic the result would be 1111 1110 binary, which is -2 in two's complement, and thus negative. A negative result out of positive operands is an overflow. The overflow flag would then be set so the program can be aware of the problem and mitigate this or signal an error. The overflow flag is thus set when the most significant bit is changed by adding two numbers with the same sign. Overflow never occurs when the sign of two addition operands are different.
Internally, the overflow flag is usually generated by an exclusive or of the internal carry into and out of the sign bit. As the sign bit is the same as the most significant bit of a number considered unsigned, the overflow flag is "meaningless" and normally ignored when unsigned numbers are added or subtracted.
The overflow flag is typically changed by all arithmetic operations, including compare instructions. In many processor architectures, the overflow flag is cleared by bitwise operations, possibly including shifts and rotates, but it may also be left undefined by these. Instructions such as multiply and divide often leave the flag undefined, or affected by the last partial result.
On many processors, addition and subtraction instructions affect both the carry/borrow and overflow flags, though only one of them will normally be of interest, depending on whether the operands represented signed or unsigned numbers.