Arithmetic and the Flags Register

Operations like ADD and SUB affect the Flags Register (F), which is essential for conditional execution.

Key Flags:

  • Z (Zero): Set if the result of an operation is zero.
  • C (Carry): Set if there is a carry-out from the most significant bit.
Instruction Description
ADD A, R Adds the 8-bit contents of R to A. Only A can be the destination.
ADD HL, DE Adds the 16-bit contents of DE to HL.

Controlling Execution with Jumps

Jumps (changing the Program Counter) allow programs to make decisions and repeat blocks of code.

Conditional Jumps These instructions check the status of a flag before jumping:

    ; CP B (Compare B with A) affects the flags
    CP  B
    JP  Z,  IS_EQUAL      ; Jump if the Zero flag is set (A=B)
    JP  NC, NO_CARRY      ; Jump if the Carry flag is NOT set

The Dedicated Loop: DJNZ

The DJNZ (Decrement and Jump if Not Zero) instruction is optimized for simple, fixed-count loops.

  • It implicitly uses the B register as the counter.
    LD   B, 10          ; Initialize counter to 10
LOOP_START:
    ; ... code to execute 10 times ...
    DJNZ LOOP_START     ; Decrement B, then jump back if B ≠ 0
    RET                 ; Loop finished