ASSEMBLY / CHAPTER 07
Carry, signed overflow, and wide addition
MasterRead flags according to the numeric contract.
By the end of this chapter
- Distinguish CF from OF
- Propagate carry between limbs
- Keep flag-producing and consuming instructions adjacent
The idea
An arithmetic result can fit one interpretation and overflow another. The carry flag describes unsigned carry out of an addition, while the overflow flag describes an unrepresentable signed result. For eight-bit 0x7F plus one, the destination becomes 0x80: unsigned 128 fits, but signed positive 128 does not. The register stores the bits; the flags describe these separate conditions.
Multiword unsigned addition uses ADD for the low part and ADC for a higher part. ADC includes the incoming carry flag in its sum. An intervening instruction that changes CF can destroy the propagation, even if the register values still look correct. Prepare constants and clear registers before the low-part ADD, and consume the carry before another flag-changing instruction. These traces do not perform I/O.
; Add 1 to the unsigned 64-bit value represented by EDX:EAX.
mov edx, 0
mov eax, 0xFFFFFFFF
add eax, 1
adc edx, 0EDX:EAX = 0x00000001:00000000.
The low 32-bit addition wraps and sets CF; ADC adds that carry to the high part.
Try it yourself
Trace 0x7F+1 and 0xFF+1 at eight-bit width and distinguish CF, OF, and stored result.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING