In programming languages, we often do arithmetic, and we need to be aware of a phenomenon called overflow. There are several situations in which overflow can occur; this note is about overflow involving integers, and primarily about addition.
We store our integers in some specific number of bytes, typically 4. A 4-byte value is made up of 32 bits, and every bit is significant. This is different from ordinary arithmetic in which we can use as much space as we like to store an integer. Because we use only a specific number of bytes to store the integer, only a certain range of values can be stored.
In assembly language, we are usually dealing with signed integers, which have a range of values from -2^31 to +2^31-1, or from -2,147,483,648 to +2,147,483,647.
Overflow occurs when, as the result of some calculation, a number is outside the range. For instance, if we try this:
2147483647 + 1
that is, the largest possible positive value in the range plus 1, the result will not be 2147483648, which is what we would normally expect, but -2147483648, the largest possible negative value. In effect, if we start at the right end of the range and keep going, we wrap around to values at the left end.
This is called overflow. There are at least two ways to detect it:
If we are subtracting instead of adding, we compute A - B by computing -B = the two-s complement of B, and then adding:
A - B = A + (-B)
This reduces the problem to addition.