Your place is saved automatically on this browser.
CALL and RET use the stack for control flow. Programmers can also use the stack to save working register pairs. The common pair operations include PUSH BC, PUSH DE, PUSH HL and PUSH AF, with matching POP instructions.
A typical pattern is PUSH BC, perform some work that changes BC, then POP BC. The caller sees the old BC restored. Notice that we save and restore a 16-bit pair; an individual PUSH B is not a normal Z80 instruction.
Test a simple pair save:
In order: BC receives $1234; PUSH BC stores the pair on the stack; LD BC,$0000 changes the live register pair; and POP BC restores the original $1234. Expected: B = $12, C = $34, BC = $1234, HL = $6000.
The correct order matters
Suppose two pairs are saved in this order:
We must remove DE first because it was pushed last. Reversing the two POP instructions would swap stored values into the wrong register pairs. Omitting either POP would also leave SP in the wrong place when the routine eventually executes RET.
A two-register-pair stack diagram
Suppose BC contains $1234 and DE contains $ABCD. Imagine, for illustration only, that SP starts at $D000. Both PUSH instructions store two bytes and reduce SP by two. The most recently pushed pair appears at the top.
POP DE: DE = $ABCD, SP = $CFFE. Then POP BC: BC = $1234, SP = $D000.
This is a drawing of the stack mechanism, not a command to configure a real stack at $D000 on your Next. The order is crucial: PUSH BC then PUSH DE must be followed by POP DE then POP BC. The data bytes are not tagged with a register name in RAM; the CPU simply reads whatever is on top into the pair you named.
Keep the caller’s return address in mind: a helper using PUSH and POP is sitting above a saved CALL return address. If one extra PUSH remains when RET runs, RET can treat register data as an address and jump somewhere unintended. The rule is to restore everything you pushed before returning.
Can I use PUSH AF?
Yes, but be cautious. PUSH AF and POP AF save and restore both the accumulator A and the flags F. That is exactly what you want if a routine must leave the caller’s flags intact — but not if you intend the caller to read flags resulting from the routine’s arithmetic. This is why a routine contract must explain what happens to both registers and flags.
