AP® Computer Science Principles · Big Idea 1 · Topic 1.4
Overflow Errors
An overflow error happens when a value outgrows the fixed number of bits storing it, so it wraps around to a tiny or negative number instead of continuing to grow.
A computer sets aside a fixed number of bits for each variable. An 8-bit counter has exactly 256 possible patterns, representing 0 through 255. Those patterns are not a suggestion, they are the whole available space. When a program tries to store a value past the top of that range, there is no bigger pattern waiting for it. The extra bit that would be needed just gets dropped, and the bits that are left spell out a much smaller number.
This is why an 8-bit counter sitting at 255 and then incremented by 1 does not become 256. In binary 255 is 11111111. Adding 1 would need a ninth bit, but there are only eight slots, so that ninth bit vanishes and the counter is left holding 00000000, which is 0. Add k values past the maximum and the counter lands on k minus 1, cycling back through the same small range over and over. Some languages use the same wraparound trick to represent negative numbers, which is why an overflowing counter can appear to flip to a huge negative value instead of zero.
Languages that let integers grow as large as available memory allows sidestep this by not committing to a fixed width up front, letting the stored representation expand as the number does, at the cost of extra memory and speed. Most ordinary fixed-width languages do not warn when overflow happens, since wrapping around is still a valid, silent operation on the bits, not a crash. Catching it is left to whoever writes the program, by checking values before they get too large, which is why overflow sits alongside input and logic errors as one of the places a program can quietly stop doing what it was built for.
Key terms
- Overflow error
- A bug where a value exceeds the maximum its fixed storage can hold and wraps to a small or negative number.
- Bit width
- The fixed number of binary digits set aside to store a value, which sets its maximum representable size.
- Wraparound
- The behavior of a fixed-width value cycling back to its minimum once it passes its maximum.
- Arbitrary-precision integer
- A number representation that grows its storage as needed instead of using a fixed bit width.
Watch it explained
- How it worksHow does a fixed number of bits make a counter wrap around instead of simply growing?
- Worked exampleShow me what happens to an 8 bit counter holding 255 when the program adds one more.
- Going furtherWhat changes when a language lets integers grow as large as the machine's memory allows?
- Common mistakeWhy isn't an overflow error something the programming language always warns you about?
Check yourself
End of topic.