Your place is saved automatically on this browser.
CALL routine tells the CPU to continue at another address and remembers where it should return. RET retrieves the saved return address. Together they let us write a routine once and use it from many places.
Here is our first complete subroutine experiment:
Follow the sequence rather than reading the source only from top to bottom. Odin starts the routine at start. LD A,$05 makes A five. CALL add_three stores the address of the next main-programme instruction, then begins add_three. The subroutine adds three, giving A = $08. Its RET returns to the LD HL,$6000 instruction in the main programme. The second RET, at the end of the main programme, returns to Odin.
Expected: A = $08, HL = $6000. The stack should be back to the condition expected by Odin once the routine has returned, because the internal CALL and RET match.
See the return point in machine code
With a $6000 starting address, these particular Z80 instructions have the following layout:
The machine-code bytes for CALL contain the destination address $6009, little-endian as 09 60. The return address $6005 is not another operand inside CALL; the CPU calculates and pushes that address onto the stack when executing the call. That distinction is one of the important ideas in this chapter.
Try this on paper: change the initial A value to $10. Without touching the subroutine, what should A contain after the call? Answer: $13.
Walk through PC and SP, one instruction at a time
We can now see exactly how the simple add_three example reaches its subroutine and returns. Assume the programme begins at $6000. We call the Stack Pointer value S because Odin supplies the real value; it must not be replaced with an invented SP address.
The fifth step is not an extra CALL. When the subroutine ends, its RET returns to the instruction after CALL, not to the top of start. The final RET is different: it returns out of our teaching programme to Odin’s own calling context.
The two bytes $05 and $60 are the little-endian representation of the 16-bit return address $6005. They are not stored in the assembler’s CALL instruction: the CPU writes them onto the live stack when CALL executes. The diagram deliberately avoids choosing a real RAM location for the stack.
