This is a recursive procedure that will print a string in reverse.
.186 ;allow pushing of immediate values .model small .stack 100h .data msg db "now$" .code main proc mov ax,@data mov ds,ax push offset msg ;push parameter on the stack call print_back add sp,2 ;remove parameter from the stack mov ax,4c00h int 21h main endp print_back proc push bp ;be nice, the bp you save may be your own mov bp,sp ;set up base pointer for stack frame push bx ;be nice push dx mov bx,[bp+4] ;unload the address of the parameter cmp byte ptr [bx],'$' ;test if we are processing an empty string je done ;not done, so call again with shorter string mov dl,[bx] ;save current character so it can be accessed later inc bx ;move to next position in string push bx ;push new position as parameter on the stack call print_back ;print a shorter string add sp,2 ;remove parameter from the stack call print_char done: pop dx pop bx mov sp,bp ;clear all local variables pop bp ret print_back endp print_char proc ;print character that is in dl push ax mov ah,02h int 21h pop ax ret print_char endp end main
Assume that msg is located at offset 100h in the
data segment.
| offset | 100 | 101 | 102 | 103 |
| character | n | o | w | $ |
Here is a stack movie as each recursive call is made. Read from the bottom to the top. When the recursive calls are finished, the values in dx will be restored in reverse order and printed as "won".
| old dx: 'w' |
| old bx: 102 |
| old bp in print_back |
| ret to print_back |
| offset of string to print (103h: $) |
| old dx: 'o' |
| old bx: 101 |
| old bp in print_back |
| ret to print_back |
| offset of string to print (102h: w$) |
| old dx: 'n' |
| old bx: 100 |
| old bp in print_back |
| ret to print_back |
| offset of string to print (101h: ow$) |
| main dx |
| main bx |
| main bp |
| return to main |
| offset of string to print (100h: now$) |