Definition
The Carry Flag is a status flag, typically occupying bit 0 (F(0)) of a processor's Flag Register, that indicates whether an unsigned arithmetic operation produced a result too large to fit in the destination register. When set, it signals that an overflow has occurred, allowing subsequent instructions to handle extended-precision arithmetic by incorporating the carry bit.
Role in Arithmetic Operations
The Carry Flag is updated automatically by arithmetic instructions such as ADD, ADC (add with carry), SUB, and SBC (subtract with borrow). In the context of an addition instruction:
- The Carry Flag (F(0)) is set only if an overflow occurs in the result of the arithmetic operation.
- It is cleared when the operation completes without overflow.
For example, when repeatedly executing an ADC H instruction on a Game Boy-style processor model and the accumulator (register A) transitions from 0x0F to 0x14, the carry-out of the lower nibble into the higher nibble constitutes an overflow. This overflow is reflected in the flag register at bit-index 0, setting the Carry Flag.
Distinction from the Half Carry Flag
The Carry Flag must not be confused with the Half Carry Flag (F(1)):
- The Half Carry Flag indicates a carry from the lower nibble (bits 0–3) to the higher nibble (bits 4–7). It is set only if a carry occurred from the lower to the higher nibble.
- The Carry Flag indicates an overflow out of the entire byte (bit 7 to bit 8).
In the Game Boy ALU execution example, a transition from 0x0F to 0x14 involves a carry between nibbles, which sets the Half Carry Flag; if the operation were to transition the accumulator beyond 0xFF, the Carry Flag would additionally be set.
Relationship with Other Flags
The Carry Flag operates alongside other status flags in the Flag Register:
- Zero flag (F(3)): set if the result of the operation is zero.
- Subtract flag (F(2)): cleared for addition operations.
- Half Carry flag (F(1)): set on a carry from bit 3 to bit 4.
- Carry flag (F(0)): set on an overflow from bit 7 outward.
Implementation in ALU Modeling
When implementing an ALU instruction such as ADD H, the executeALUInstruction function must update the Flag Register as follows:
- Store the sum of register H and register A back into register A.
- Set the Zero flag (F(3)) if the result equals
0x00. - Clear the Subtract flag (F(2)).
- Set the Half Carry flag (F(1)) only when a carry propagates from the lower nibble to the higher nibble.
- Set the Carry flag (F(0)) only when the arithmetic operation produces an overflow.
Use in Multi-Byte Arithmetic
The Carry Flag serves a critical role in extended-precision arithmetic. Instructions such as ADC (add with carry) include the current state of the Carry Flag as an additional operand, allowing chains of additions to correctly propagate carries across multiple bytes. This makes the Carry Flag both an indicator of overflow and an input to subsequent arithmetic operations.