Subroutines and the Stack in 8086 Assembly (CALL, RET, PUSH, POP)

As programs grow, the same block of code is needed in several places. Copying it everywhere is error-prone; calling it as a subroutine is not. This tutorial explains the two mechanisms that make subroutines work: CALL and RET for the jump there and back, and PUSH and POP for saving values on the stack. It builds on MOV, ADD and SUB, and Emu8086 setup is in the install guide.

CALL and RET are a matched pair

CALL jumps to a subroutine and, crucially, pushes the return address onto the stack first. RET at the end of the subroutine pops that address back and jumps to it, so execution continues just after the CALL. Every CALL must be matched by a RET on every path through the subroutine. A subroutine that falls off the end without a RET will jump to whatever value happens to sit on the stack, which is one of the most confusing bugs in assembly language.

PUSH and POP save values

The stack is a last-in, first-out store. PUSH puts a value on it and moves the stack pointer; POP takes the most recently pushed value back. That is how a routine protects a register it needs to use, and how the sorting example in this series protects CX across an inner loop. Pushes and pops must balance: an extra push without a matching pop leaves the stack pointer wrong, and the next RET will return to the wrong address.

The complete program

The program below adds 7 and 5 in a subroutine, saves that result on the stack while AX is reused, then adds it to 3. Follow the stack pointer in the emulator while single-stepping: it should move on the CALL, the PUSH and the POP, and return to its starting value by the final RET.

ORG 100h

MOV AX, 7
MOV BX, 5
CALL add_two
MOV CX, AX
PUSH CX
MOV AX, 3
POP BX
ADD AX, BX
RET

add_two PROC
ADD AX, BX
RET
add_two ENDP

What you should see

After the CALL, AX should hold 12, because the subroutine added BX (5) to AX (7). CX then holds 12, and after the push, reuse of AX and pop, BX holds 12 again while AX holds 3. The final ADD gives AX equal to 15. If AX ends up as something else, the most likely cause is an unbalanced push and pop, so watch the stack pointer value at the start and at the end: in a correct run it is the same.

Passing values in registers

This example passes its inputs in AX and BX and returns its answer in AX. That convention, inputs in named registers and the result in a named register, is the simplest calling convention and the right one for beginner programs. Larger programs sometimes pass values on the stack instead, but the principle is the same: the caller and the subroutine must agree, in advance, on where each value lives.

Next steps

Macros look similar but work differently: macros and emu8086.inc explain the difference. For the debugging techniques that catch unbalanced stacks, see step debugging. The opcode reference covers CALL, RET, PUSH and POP, and the home page links the whole series.

Similar Posts