7.3.4 Using Local Variables

In high-level languages, local variables are visible only within a procedure. In Microsoft languages, these variables are usually stored on the stack. In assembly-language programs, you can also have local variables. These variables should not be confused with labels or variable names that are local to a module, as described in Chapter 8, “Sharing Data and Procedures among Modules and Libraries.”

This section outlines the standard methods for creating local variables. The next section shows how to use the LOCAL directive to make the assembler automatically generate local variables. When you use this directive, the assembler generates the same instructions as those used in this section but handles some of the details for you.

If your procedure has relatively few variables, you can usually write the most efficient code by placing these values in registers. Local (stack) data is more efficient when you have a large amount of local data for the procedure.

Summary: Local variables are stored on the stack.

To use local variables you must save stack space for the variable at the start of the procedure. The variable can then be accessed by its position in the stack. At the end of the procedure, you need to restore the stack pointer, which restores the memory used by local variables.

This example subtracts two bytes from the SP register to make room for a local word variable. This variable can then be accessed as [bp-2].

push ax ; Push one argument

call task ; Call

.

.

.

task PROC NEAR

push bp ; Save base pointer

mov bp, sp ; Load stack into base pointer

sub sp, 2 ; Save two bytes for local

; variable

.

.

.

mov WORD PTR [bp-2], 3 ; Initialize local variable

add ax, [bp-2] ; Add local variable to AX

sub [bp+4], ax ; Subtract local from argument

. ; Use [bp-2] and [bp+4] in

. ; other operations

.

mov sp, bp ; Clear local variables

pop bp ; Restore base

ret 2 ; Return result in AX and pop

task ENDP ; two bytes to clear parameter

Notice that the instruction mov sp,bp at the end of the procedure restores the original value of SP. The statement is required only if the value of SP is changed inside the procedure (usually by allocating local variables). The argument passed to the procedure is removed with the RET instruction. Contrast this to the example in Section 7.3.2, “Passing Arguments on the Stack,” in which the calling code adjusts the stack for the argument.

Figure 7.2 shows the state of the stack at key points in the process.