Chapter 8.2: Procedures
Introduction
Learning Outcomes
Define procedures with PROC / ENDP; tell an assembler directive from a CPU instruction.
Trace, through SP and IP, how the return address is pushed by CALL and popped by RET.
Pass data to a procedure and get results back through registers, memory variables and the stack (BP frame).
Preserve registers with PUSH/POP, keep the stack balanced and avoid the typical bugs.
Introduction
What Is a Procedure?
- A procedure is a piece of code that performs one specific task (a function or subroutine in high-level languages).
- The program calls it with
CALL. - When the task is done,
RETreturns right after the point of the call. - The code is written once and called from many places.
- Procedures make a program more structured and easier to follow.
Definition
Defining a Procedure
name PROC ; start (NEAR by default) ; procedure body goes here RET name ENDP ; end
name: the procedure's name; it must be the same at both ends.- The name follows the rules for labels (it cannot start with a digit).
- A procedure must contain at least one
RET.
Where does a procedure go?
ORG 100h
CALL p1
RET ; main program ends
p1 PROC ; after the RET:
; ... ; never fallen into
RET
p1 ENDP
END
Placed after the main program's RET, procedures cannot be executed by accidentally "falling into" them. If one comes first, jump over it with JMP.
Definition
Directives and Instructions
| Item | Kind | Role |
|---|---|---|
| PROC / ENDP | Assembler directive | Tells the assembler where the procedure starts and its type (NEAR/FAR). Not translated into machine code; takes no memory. |
| CALL | CPU instruction | Pushes the return address and jumps to the procedure. |
| RET | CPU instruction | Pops the return address and jumps there. Used to return both from a procedure and from a .COM program. |
| END | Assembler directive | Marks the end of the source file. |
INT 20h, which ends the program.Definition
Modular Programming
; main.asm EXTRN show:NEAR ; in another file ... CALL show ; tools.asm PUBLIC show ; exported show PROC NEAR ... RET show ENDP
- Large programs are split into procedures, and procedures into separate source files (modules).
PUBLICmakes a procedure name visible to other modules;EXTRNdeclares that a name is defined in another module, along with its type (NEAR/FAR).- Each module is assembled separately into an object file (.OBJ); the linker joins them and fills in the addresses in CALL instructions.
- Frequently used object files are collected in a library (.LIB); the linker pulls in only the procedures the program needs.
- In emu8086, shared code is usually added with
INCLUDE: the file's text is inserted into the source and assembled as one piece (emu8086.inc).
CALL and RET
CALL and RET Step by Step
Start: IP = 0100h, SP = FFFEh. Next instruction: CALL m1 (3 bytes: E8 04 00).
CALL first pushes the return address (the next instruction, 0103h): SP = FFFCh, [FFFCh] = 0103h.
Then IP ← 0103h + 0004h = 0107h: the first instruction of the procedure.
MOV BX, 5 executed, IP = 010Ah. The stack is unchanged.
RET: IP ← [SP] = 0103h, SP = FFFEh. Execution continues right after the CALL.
MOV AX, 2 → IP = 0106h. The RET here pops 0000h and ends the program.
CALL and RET
Kinds of CALL / RET
| Instruction | Code | Bytes | Pushed / popped | Description |
|---|---|---|---|---|
| CALL near | E8 rel16 | 3 | IP | Direct call within the same segment (default). |
| CALL reg/mem | FF /2 | 2–4 | IP | Indirect near call: CALL BX, CALL [table+SI]. |
| CALL far | 9A ofs seg | 5 | CS, then IP | Procedure in another segment; CS:IP change together. |
| RET | C3 | 1 | IP | Near return. |
| RETF | CB | 1 | IP, then CS | Far return (FAR procedure). |
| RET n | C2 n16 | 3 | IP, SP += n | On return, also discards n bytes of parameters from the stack. |
name PROC NEAR (the default) or name PROC FAR, the assembler encodes each RET inside the procedure accordingly (C3 / CB). In single-segment .COM examples, procedures are NEAR.CALL and RET
Far Procedure: Stack Layout
- A FAR procedure lives in another code segment; reaching it requires changing both CS and IP.
CALL FARpushes CS first, then IP: 4 bytes on the stack.RETFpops IP first, then CS.- A near
CALLpushes only IP (2 bytes), andRETpops only IP. - The procedure type and the return instruction must match: with
PROC FAR, the assembler encodes the RET inside as RETF (CB). - A .COM program runs in a single segment, so near calls are enough; .EXE programs with several code segments need far calls.
CALL and RET · Step through the code
Code Trace: PUSH CS + CALL with RETF
AX = 5. This code imitates the two pushes of a CALL FAR with two separate instructions.
PUSH CS: the code segment (0700h in this run) is pushed; the first half of a far call.
The near CALL farp pushes the return address (0107h) and jumps to 010Bh. The stack now has the far-call layout: IP on top, CS below it.
SHL AX, 1: AX = 000Ah.
RETF pops two words: IP = 0107h, CS = 0700h; SP goes up by 4 to FFFEh.
Execution continues at ADD AX, 1: AX = 000Bh. A real CALL FAR (9A, 5 bytes) does both pushes in one instruction.
ORG 100h MOV AX, 5 PUSH CS ; first half of a far call CALL farp ; pushes IP ADD AX, 1 RET farp PROC SHL AX, 1 RETF ; IP first, then CS farp ENDP
CALL and RET · Step through the code
Code Trace: Indirect CALL through a Table and a Register
AX = 6. table is an array of words holding the addresses of two procedures (0114h, 0116h).
SI = 2: the 2nd entry of the table (each entry is 2 bytes).
CALL table[SI]: the target is read from memory at [table+2] = 0116h. Return address 010Ah pushed, IP = 0116h.
twice: SHL AX, 1 → AX = 12.
RET: IP = 010Ah, back in the main program.
BX = OFFSET add_one = 0114h.
CALL BX: the target comes from a register. Return 010Fh pushed, IP = 0114h.
add_one: AX = 13.
RET → 010Fh. Which procedure to call was chosen at run time through SI or BX.
MOV AX, 6 MOV SI, 2 ; 2nd op (× 2) CALL table[SI] ; indirect, memory MOV BX, OFFSET add_one CALL BX ; indirect, register RET table DW add_one, twice add_one: INC AX RET twice: SHL AX, 1 RET
CALL and RET
Menu with a Jump Table
MOV AH, 1 INT 21h ; AL = '1'..'3' SUB AL, '1' ; 0..2 CMP AL, 2 JA invalid ; range check MOV BL, AL MOV BH, 0 SHL BX, 1 ; 2-byte entries CALL ops[BX] invalid: RET ops DW sum, diff, prod
- Each option is a procedure; their addresses sit in order in
ops. - The key becomes a table index: '1' → 0, '2' → 1, '3' → 2. Addresses are 2 bytes, so the index is doubled (
SHL BX, 1). JAis unsigned: key '0' gives 0 − 1 = FFh, which is above 2 and rejected too. One check covers both ends.- Without the check, a bad key would call whatever bytes lie past the table.
| Key | BX | Called |
|---|---|---|
| 1 | 0 | sum |
| 2 | 2 | diff |
| 3 | 4 | prod |
| 0 · 9 | — | none (RET) |
CALL and RET · Step through the code
Code Trace: A Simple Procedure
The program starts at 0100h. ORG, PROC, ENDP, END produce no bytes.
CALL m1: 0103h is pushed, IP = 0107h.
BX = 0005h.
RET: 0103h is popped → IP = 0103h, SP = FFFEh.
AX = 0002h.
RET: 0000h is popped → IP = 0000h, SP = FFFEh + 2 = 0000h. The INT 20h in the PSP ends the program. Result: AX = 2, BX = 5.
ORG 100h CALL m1 ; 0100h: E8 04 00 MOV AX, 2 ; 0103h: B8 02 00 RET ; 0106h: C3 → DOS m1 PROC MOV BX, 5 ; 0107h: BB 05 00 RET ; 010Ah: C3 → caller m1 ENDP END
CALL and RET
Machine Code in Memory
- The example program takes only 11 bytes of memory:
E8 04 00 B8 02 00 C3 BB 05 00 C3. CALL m1stores the target not as an absolute address but as a displacement from the next instruction (rel16). That is why the code still works when moved elsewhere in memory.- 16-bit values are stored little-endian: low byte first (04), then high byte (00).
- The procedure name (
m1) exists only for the assembler; the machine code keeps just the address 0107h.
CALL and RET
Cost of CALL and RET
| Instruction (8086) | Clocks |
|---|---|
| CALL near | 19 |
| CALL reg | 16 |
| CALL FAR | 28 |
| RET | 8 |
| RETF | 18 |
| PUSH reg | 11 |
| POP reg | 8 |
Call overhead
- Call overhead of a procedure that saves two registers: 19 + 8 + 2 × (11 + 8) = 65 clocks.
- On a 5 MHz 8086 a clock is 200 ns: 65 × 200 ns = 13 µs.
- Called 1000 times, the overhead is 13 ms.
- A macro has no such overhead, but copies its body at every use.
Parameters
Ways to Pass Parameters
number1, result. Easy, but it ties the procedure to those variables.PUSH, read through BP and removed with RET n. The method compilers use.Parameters
By Value or by Reference?
The procedure gets a copy of the data (AX = 5). Even if it changes the copy, the variable in memory stays the same. Fast and safe for small data such as a single number.
The procedure gets the data's address (SI = OFFSET a). Through [SI] it reads and can change the variable itself. For arrays, strings and variables the procedure must update.
MOV AX, a ; value: AX holds a copy of a CALL twice ; AX doubles, a stays the same LEA SI, a ; address: SI = OFFSET a CALL twice_m ; [SI] doubles, a changes
LEA SI, a and MOV SI, OFFSET a give the same result: the address of a. MOV SI, a instead loads the value stored in a, not its address; a common mix-up when passing by reference.Parameters · Step through the code
Code Trace: Swap by Reference
SI and DI carry the addresses of a and b (0113h, 0115h): the procedure gets locations, not values.
CALL swap: return address 0109h pushed, SP = FFFCh.
swap will use AX, so it saves it first (SP = FFFAh).
MOV AX, [SI]: reads the value of a (1234h).
XCHG AX, [DI]: AX and b trade places in one instruction: b = 1234h, AX = 00FFh.
MOV [SI], AX: a = 00FFh. The swap is done in memory.
POP AX and RET: AX gets its old value (0000h) back, SP = FFFEh; a and b stay swapped.
ORG 100h LEA SI, a LEA DI, b CALL swap RET swap PROC ; In: SI, DI (addrs) PUSH AX MOV AX, [SI] XCHG AX, [DI] MOV [SI], AX POP AX RET swap ENDP a DW 1234h b DW 00FFh
Parameters
Parameters in Registers
- In the example, the AL and BL registers hold the two parameters.
- The
m2procedure multiplies AL by BL and leaves the result in AX. CALL m2calls the procedure;RETreturns to the caller.- m2 is called twice: in the second call AL carries the result of the first, because MUL changes AX (and so AL).
| MUL source | Operation | Result |
|---|---|---|
| 8-bit | AL × source | AX |
| 16-bit | AX × source | DX:AX |
MUL is unsigned; if the upper half of the result (AH or DX) is not 0, CF = OF = 1. The source cannot be an immediate: MUL 2 is invalid.
Parameters · Step through the code
Code Trace: Parameters in Registers
AL = 1 (MOV AL, 1 = B0 01, 2 bytes).
BL = 2.
1st call: return address 0107h pushed, IP = 010Bh.
MUL BL: AX = 1 × 2 = 0002h. AH = 0 → CF = OF = 0.
RET → IP = 0107h: the second CALL.
2nd call: this time the return address 010Ah is pushed. Same procedure, different return point.
MUL BL: AL is now 2 → AX = 2 × 2 = 0004h.
RET → IP = 010Ah.
RET: back to DOS. Result AX = 0004h.
ORG 100h MOV AL, 1 ; 1st parameter MOV BL, 2 ; 2nd parameter CALL m2 ; 0104h: E8 04 00 CALL m2 ; 0107h: E8 01 00 RET ; 010Ah: to DOS m2 PROC ; 010Bh MUL BL ; AX = AL * BL RET ; to caller m2 ENDP END
Parameters · Step through the code
Code Trace: Returning the Result in CF
The digit procedure converts the character in AL to a number and reports success in CF (as DOS services do). AL = '7' = 37h.
CALL digit; SUB AL, '0': 37h − 30h = 7.
CMP AL, 10: 7 − 10 needs a borrow → CF = 1 (value in 0…9).
CMC: CF = 0 → “a digit”.
RET; the caller can test CF (JC/JNC). BL = 7 saved.
AL = 'x' = 78h; second call: 78h − 30h = 48h (72).
CMP AL, 10: 72 ≥ 10, no borrow → CF = 0.
CMC: CF = 1 → “not a digit”. AL is now garbage (48h) and must not be used.
RET: the result is in the flag. The caller can branch with JC error.
MOV AL, '7' CALL digit ; CF = 0 → AL = value MOV BL, AL MOV AL, 'x' CALL digit ; CF = 1 → not a digit RET digit PROC ; In: AL, Out: CF SUB AL, '0' CMP AL, 10 ; 0..9 → borrow, CF = 1 CMC ; digit: CF = 0 RET digit ENDP
Parameters
Returning Several Results
divmod PROC ; In: AX, BL (divisor) CMP BL, 0 ; Out: AL = quotient JE error ; AH = remainder DIV BL ; CF = 1: BL is 0 CLC RET error: STC RET divmod ENDP
- Register pair: a 32-bit result in DX:AX (like 16-bit MUL), quotient and remainder in AL and AH.
- Flag + register: CF reports success, the register holds the value; the caller tests
JCfirst. - Memory: any number of results are written to a buffer at a given address.
| Input | Result |
|---|---|
| AX = 100, BL = 7 | AL = 0Eh (14), AH = 02h, CF = 0 |
| AX = 100, BL = 0 | CF = 1, AX unchanged (0064h) |
| AX = 1000, BL = 2 | quotient 500 does not fit in AL: divide error (INT 0) |
Parameters
Preserving Registers
Problem
If a procedure quietly changes a register the caller relies on (e.g. the loop counter CX), the caller breaks.
Documentation
; m2: computes AL * BL ; In : AL, BL (unsigned) ; Out : AX = AL * BL ; Clobber: CF, OF
Solution: PUSH / POP
show PROC PUSH AX ; save what PUSH SI ; you use ; ... AX and SI are used POP SI ; in REVERSE POP AX ; order RET show ENDP
The register that returns the result (e.g. AX) is not preserved; otherwise the result would be lost.
Parameters · Step through the code
Code Trace: Saving the Counter with PUSH CX
The main loop prints 2 rows: counter CX = 2. The stars procedure also uses CX in its inner loop.
CALL stars: return address 0106h pushed, SP = FFFCh.
PUSH CX: the caller's counter (2) is saved on the stack.
Inner counter CX = 3; AX = 0E23h (AH = 0Eh teletype, AL = '#').
The inner loop runs INT 10h three times: ###. After LOOP, CX = 0.
POP CX: the caller's counter is back, CX = 2.
RET: returns to 0106h, SP = FFFEh.
Main LOOP row: CX = 1 → call again for the second row.
The second call works the same way: ### is printed, CX = 1 restored.
LOOP: CX = 0 → the loop ends. 6 characters on screen. Without PUSH/POP, CX would be 0 on return, and LOOP would make it FFFFh and loop almost forever.
MOV CX, 2 ; main loop: 2 rows row: CALL stars LOOP row RET stars PROC PUSH CX ; caller's counter MOV CX, 3 ; inner counter MOV AX, 0E23h ; AH = 0Eh, AL = '#' inner: INT 10h LOOP inner POP CX ; counter back RET stars ENDP
Parameters
Caller-Saved or Callee-Saved?
| Criterion | Callee saves (PUSH/POP in the procedure) | Caller saves (around the CALL) |
|---|---|---|
| Where is the code? | once, in the procedure | at every call site |
| Needless saving | saved even if the caller doesn't use it | only the registers really needed |
| Risk of forgetting | low: written in one place | high: needed again at every call |
| Best for | library procedures | when the old value of an output register is needed |
again: PUSH CX ; caller: counter CALL read_num ; result in CX ADD total, CX POP CX ; counter back LOOP again
Parameters · Step through the code
Code Trace: Single Exit Point
The find procedure searches the CX-element array at SI for AL (7); it returns the result in CF and BX.
CALL find: return address 010Bh pushed.
The procedure will change CX and SI, so it saves both; SP = FFF8h. BX = 0 (index).
arr[0] = 3 ≠ 7: SI and BX advance, LOOP brings CX down to 4.
arr[1] = 9 ≠ 7: BX = 2, CX = 3.
arr[2] = 7: ZF = 1, JE found jumps. The loop ends early, but two saved values are still on the stack.
STC: CF = 1 → “found”. If not found, CLC and JMP done would arrive at the same place.
Both paths meet at the done label: the POPs always run, and SI and CX get their old values back.
RET returns to the right address (010Bh): CF = 1, BX = 2. Had JE been replaced by a direct RET, the SI value on top (011Fh) would have been taken as the return address.
ORG 100h LEA SI, arr MOV CX, 5 MOV AL, 7 CALL find ; CF = 1: found RET find PROC ; In: SI, CX, AL PUSH CX PUSH SI XOR BX, BX ; Out: BX = index scan: CMP [SI], AL JE found INC SI INC BX LOOP scan CLC ; not found JMP done found: STC done: POP SI ; single exit point POP CX RET find ENDP arr DB 3, 9, 7, 1, 4
Parameters · Step through the code
Passing Parameters on the Stack (with BP)
The caller puts the parameters on the stack; the procedure reads them through BP.
AX = 7.
1st parameter on the stack: [FFFCh] = 0007h.
AX = 3.
2nd parameter: [FFFAh] = 0003h.
CALL: return address 010Bh → [FFF8h]. IP = 010Fh.
The old BP is saved: [FFF6h] = 0000h.
MOV BP, SP: BP = FFF6h becomes a fixed frame pointer.
[BP+6] = [FFFCh] = 0007h → AX = 7.
[BP+4] = [FFFAh] = 0003h → AX = 000Ah.
BP gets its old value back; SP = FFF8h (return address on top).
RET: IP = 010Bh, SP = FFFAh.
ADD SP, 4: both parameters are discarded, SP = FFFEh. The stack is balanced.
The program ends.
ORG 100h MOV AX, 7 PUSH AX ; 1st parameter MOV AX, 3 PUSH AX ; 2nd parameter CALL SUM2 ADD SP, 4 ; drop parameters RET SUM2 PROC PUSH BP MOV BP, SP MOV AX, [BP+6] ; 1st parameter ADD AX, [BP+4] ; 2nd parameter POP BP RET SUM2 ENDP
[BP+0] = old BP, [BP+2] = return address, [BP+4] = the last parameter pushed. Instead of ADD SP, 4, the procedure could also end with RET 4.
Parameters
Stack Frame and Local Variables
PUSH BP MOV BP, SP SUB SP, 4 ; local space MOV [BP-2], AX ; local 1 ... MOV SP, BP ; drop locals POP BP RET 4 ; drop 2 params
SUB SP, 4reserves two local words on the stack: [BP−2], [BP−4].MOV SP, BPreleases the local space in one instruction.- Parameters sit at positive BP offsets, locals at negative ones.
Parameters · Step through the code
Code Trace: A Local Variable on the Stack
Parameter x = 9 is in AX. The procedure will keep x in a local variable and compute x·x + x.
CALL: return address 0106h → [FFFCh].
PUSH BP: the caller's BP (0000h) is saved.
MOV BP, SP: BP = FFFAh, the fixed point of the frame.
SUB SP, 2: one word of local space; [BP−2] = FFF8h.
MOV [BP−2], AX: local = 9. [BP...] addresses use the SS segment by default.
MUL AX: AX = 81 (DX = 0). AX changed, but x is still in the local.
ADD AX, [BP−2]: 81 + 9 = 90 = 005Ah.
MOV SP, BP: the local space is released in one instruction, SP = FFFAh.
POP BP, RET: BP = 0, SP = FFFEh, back in the caller. Result AX = 90.
MOV AX, 9 CALL sq_plus ; AX = x·x + x RET sq_plus PROC PUSH BP MOV BP, SP SUB SP, 2 ; local [BP-2] MOV [BP-2], AX ; local = x MUL AX ; AX = x·x ADD AX, [BP-2] ; + x MOV SP, BP ; drop local POP BP RET sq_plus ENDP
Example Programs
Hello World Message
- Printing a message with a procedure.
LEA SI, msg: loads the address of the string msg into SI (parameter = address).CALL print_me: calls the print_me procedure.RET: returns to the operating system.print_meprints a null-terminated (0) string character by character.b.[SI]is emu8086 shorthand forBYTE PTR [SI]:CMP [SI], 0does not give the operand size, so it is stated explicitly.
ORG 100h LEA SI, msg ; address of msg CALL print_me RET ; to DOS print_me PROC ; ............ print_me ENDP msg DB 'Hello World!', 0 END
Example Programs · Step through the code
Code Trace: print_me
SI points to the first character of the string ('H').
CALL print_me: the return address (the RET on line 4) is pushed.
[SI] = 'H' (48h) ≠ 0 → ZF = 0, JE does not jump.
AL = 48h, AH = 0Eh, INT 10h → H.
SI = msg+1, back to next_char.
Next pass: 'e' is printed. AL = 65h, SI = msg+2.
3 more iterations: "llo" is printed. AL = 6Fh, SI = msg+5.
6 more iterations: " World" is printed (the space is a character too: 20h). AL = 64h, SI = msg+11.
Next pass: '!' is printed. AL = 21h, SI = msg+12.
[SI] = 0 → ZF = 1, JE stop jumps.
The procedure's RET pops the return address → back to line 4.
The main program's RET returns to DOS. On screen: Hello World!
ORG 100h LEA SI, msg ; SI = address of msg CALL print_me RET ; to DOS print_me PROC next_char: CMP b.[SI], 0 ; zero? JE stop ; yes: done MOV AL, [SI] ; next ASCII char MOV AH, 0Eh ; teletype function INT 10h ; print AL ADD SI, 1 ; next character JMP next_char ; loop back stop: RET ; to caller print_me ENDP msg DB 'Hello World!', 0 END
Example Programs · Step through the code
Code Trace: Adding Two Variables
The parameters are in memory variables: number1 = 5, number2 = 3.
CALL AddNumbers (0100h, 3 bytes): return address 0103h is pushed.
AX = number1 = 0005h.
AX = 5 + 3 = 0008h; the result is nonzero, no carry.
result = 0008h (08 00 in memory).
RET → IP = 0103h.
RET → DOS. DW ? means the initial value is undefined (emu8086 uses 0).
ORG 100h start: CALL AddNumbers ; call it RET ; to DOS AddNumbers PROC MOV AX, number1 ; AX = first number ADD AX, number2 ; AX += second number MOV result, AX ; store the result RET ; end of procedure AddNumbers ENDP number1 DW 5 ; first number 5 number2 DW 3 ; second number 3 result DW ? ; holds the result
Example Programs · Step through the code
Code Trace: Address and Count as Parameters
The array sum as a reusable procedure: SI = address of the array.
CX = 5 elements.
CALL sum: return address pushed.
AL = 0.
+5 → AL = 5; SI advances, CX = 4.
+4 → AL = 9; SI advances, CX = 3.
+5 → AL = 14; SI advances, CX = 2.
+2 → AL = 16; SI advances, CX = 1.
+1 → AL = 17; SI advances, CX = 0 → the loop ends.
RET: back to the caller, the result in AL.
m = 11h = 17.
The program ends. The same procedure can be called for another array just by changing SI and CX.
ORG 100h LEA SI, vector ; param 1: address MOV CX, 5 ; param 2: count CALL sum MOV m, AL ; result is in AL RET sum PROC ; In: SI, CX MOV AL, 0 ; Out: AL = sum again: ADD AL, [SI] INC SI LOOP again RET sum ENDP vector DB 5, 4, 5, 2, 1 m DB 0
Example Programs
Parameter Block
LEA BX, block CALL calc ; result = a × b + c RET calc PROC ; In: BX = block address PUSH AX PUSH DX ; MUL writes DX too MOV AX, [BX] ; a MUL WORD PTR [BX+2] ; × b ADD AX, [BX+4] ; + c MOV [BX+6], AX ; result POP DX POP AX RET calc ENDP block DW 12, 7, 5, ?
- A single register (BX) carries any number of parameters: the block is read at fixed offsets ([BX+2], [BX+4]).
- The result goes into the block too: 12 × 7 + 5 = 89 (0059h).
- The same procedure is called with another block just by changing BX.
- Document the block layout (what sits at which offset) in the procedure's header comment.
Example Programs
Testing a Procedure
Try a procedure not only with “normal” input but also with edge cases. Results for the find procedure (array: 3, 9, 7, 1, 4):
| Case | AL | CX | CF | BX | Verdict |
|---|---|---|---|---|---|
| first element | 3 | 5 | 1 | 0 | correct |
| last element | 4 | 5 | 1 | 4 | correct |
| not in the array | 8 | 5 | 0 | 5 | correct; BX is meaningless, look only at CF |
| one-element search | 9 | 1 | 0 | 1 | correct: 9 is the 2nd element, outside the range searched |
| empty array | 7 | 0 | 1 | 2 | wrong: with CX = 0, LOOP runs 65,536 times |
LOOP decrements CX first and then tests for zero: 0 − 1 = FFFFh. The search runs 65,536 iterations and “finds” the 7 in memory (BX = 2); with a truly empty array it would read past the end.
Handle the empty array with JCXZ before the loop: if CX = 0, do CLC and go straight to the done label. Also check in every test that CX and SI are preserved.
Example Programs
Nested Calls
main is about to call A. SP = FFFEh.
CALL A: 0103h pushed, SP = FFFCh.
CALL B from inside A: 0115h pushed, SP = FFFAh. Two return addresses are on the stack.
B's RET pops 0115h from the top: back to A (LIFO).
A's RET pops 0103h: back to main. Last called, first to return.
Example Programs
How Much Stack?
- A program's stack requirement is the sum of the bytes accumulated along the deepest path in its call tree.
- Each near CALL adds a 2-byte return address, each PUSH 2 bytes.
| Path | Calculation | Bytes |
|---|---|---|
| main → A → B | 2 + 4 + 2 + 2 | 10 |
| main → C | 2 + 6 | 8 |
- In a program that starts with SP = FFFEh, SP goes no lower than FFF4h.
- A and C are never on the stack at the same time: by the time C is called, A's bytes have already been popped.
Recursion
Recursion
- Recursion: a procedure calling itself (directly or through another procedure).
- Each call pushes a new return address and its own saved values: the values of each level stay separate.
- A base case (stopping condition) is essential; without it every call eats 2 more bytes and the stack overflows.
- The problem shrinks at each step into a smaller copy of itself: printing 472 = printing 47 + printing '2'.
- Typical examples: printing numbers, factorial, walking a tree or a directory.
Recursion · Step through the code
Code Trace: Printing a Number Recursively
AX = 472 (01D8h); CALL show: return address 0106h pushed.
472 / 10: AX = 47 (2Fh), DX = 2. The last digit (2) is pushed.
AX ≠ 0: show calls itself; return address 0116h (the done label) pushed.
Second level: 47 / 10 → AX = 4, digit 7 pushed; CALL again.
Third level: 4 / 10 → AX = 0, digit 4 pushed. AX = 0: the base case, JZ done. SP at its deepest: FFF2h.
POP AX = 4 → '4' is printed. The digit pushed last comes out first.
RET goes to 0116h, the done line of the second level: POP AX = 7 → '7'.
First level: POP AX = 2 → '2'. The screen shows 472.
The last RET returns to 0106h; SP = FFFEh. Each level kept its digit on the stack, so no extra variable was needed.
ORG 100h MOV AX, 472 CALL show RET show PROC ; In: AX (unsigned) XOR DX, DX MOV BX, 10 DIV BX ; AX = quot., DX = digit PUSH DX OR AX, AX ; more digits? JZ done CALL show ; upper digits first done: POP AX ADD AL, '0' MOV AH, 0Eh INT 10h RET show ENDP
Recursion
Recursion or Loop?
| Criterion | Recursion (show) | Loop (divide + LOOP) |
|---|---|---|
| Code | short; close to the problem's definition | needs a counter and a separate print loop |
| Stack | return address + digit per level: 4 bytes | 2 bytes per digit |
| Time | CALL + RET at every level (19 + 8 clocks) | no call overhead |
| Risk | unbounded depth overflows the stack | bounded stack use |
For show, the number of levels = the number of digits. 65,535 → 5 levels: 5 × 2 (return) + 5 × 2 (digit) = 20 bytes; SP goes no lower than FFEAh.
The test must come before the CALL. For AX = 0 one digit (0) is still printed: the number 0 comes out as '0' with no extra code.
Common Bugs · Step through the code
Code Trace: Unbalanced PUSH / POP
AX = 1234h.
CALL: return address 0106h pushed.
PUSH AX: 1234h is pushed on top of the return address.
RET pops whatever is on top: IP = 1234h! The CPU jumps to a random address; the program crashes or behaves unpredictably.
ORG 100h MOV AX, 1234h ; 0100h: B8 34 12 CALL bad ; 0103h: ret = 0106h RET ; 0106h bad PROC PUSH AX ; AX saved... ; ... work ... RET ; forgot POP AX! bad ENDP
Common Bugs · Step through the code
Code Trace: Near CALL, Far Return
AX = 5. The farp procedure ends with RETF, but the call is near.
A near CALL pushes only IP (0106h): 2 bytes on the stack.
SHL AX, 1: AX = 000Ah.
RETF pops two words: IP = 0106h and, as CS, whatever it finds on the stack, here the 0000h DOS pushed for the .COM program. SP = 0000h.
The CPU jumps to 0000:0106h: that is the interrupt vector table, not program code. The program crashes; ADD AX, 1 never runs.
ORG 100h MOV AX, 5 CALL farp ; near CALL: IP only ADD AX, 1 RET farp PROC SHL AX, 1 RETF ; pops IP and CS! farp ENDP
Common Bugs
Common Bugs
p1 PROC … p2 ENDP → assembler error.Common Bugs
More Procedure Bugs
MOV SI, arr loads the array's first word, not its address; the procedure reads from an unrelated address.Lab · 8086 instructions step by step
Lab: Procedures
Summary
Summary
Summary
Exercises
- The
CALL pat address 0120h calls p at 0100h. What is the machine code? What is pushed? - In the m2 example, what would the final AX be if
MOV AL, 3were added before the secondCALL m2? - With SP = FFFEh, 3 CALLs run in a row (no RET). What is SP?
- Why is it wrong to call a procedure that clobbers CX inside a LOOP? Suggest two fixes.
- Write an
upperprocedure that converts a lowercase letter in AL to uppercase (input/output AL). - Change print_me so that it returns the number of characters printed in CX.
Hints / answers
- Next address 0123h; 0100h − 0123h = −23h = FFDDh →
E8 DD FF. 0123h is pushed. - First call AX = 2; then AL = 3 → AX = 3 × 2 = 0006h.
- Each CALL takes 2 bytes: FFFEh − 6 = FFF8h.
- The LOOP counter is clobbered and the loop runs the wrong number of times. Use
PUSH CX/POP CXin the procedure, or save it in the caller before the call. cmp al,'a'/jb done/cmp al,'z'/ja done/sub al, 20h/done: retMOV CX, 0at the start,INC CXfor each character; CX is an output, so it is not preserved.
Summary
References
- emu8086 documentation: 8086 Assembler Tutorial for Beginners (Part 8: Procedures).
- Intel, The 8086 Family User's Manual, 1979: CALL, RET and stack operations.
- Barry B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009: Section 6.3 "Procedures".
- Kip R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014: Chapter 5 "Procedures".