Subroutine Parameters
The simplest kind of subroutine performs an identical function each time it is called and required no further information.
There are two main forms of parameters:
- Value parameters
- Reference parameters
Value Parameters
In this case the additional information will be some static value. If your function uses a value then you are passing by value.
Reference Parameters
These are the addresses of variables and not the values themselves. This would be useful if the subroutine changes the memory contents in-place, as opposed to returning a value.
This is known as pass by reference.
Using Registers for parameters
This is the simplest method of passing parameters into subroutines.
Both types of parameter can be passed this way.
Example - Pass by Value
Call procedure to determine bigger of 2 numbers. The numbers are passed in eax and ebx
. Result returned in eax
.
...
mov eax, first
mov ebx, second ; calling
call bigger ; sequence
mov max, eax
...
bigger: proc
cmp eax, ebx
jl second_big
ret
second_big:
mov eax, ebx
ret
bigger: endp
Example - Pass by Reference
Swap 2 variables by passing their addresses in eax
and ebx
.
...
lea eax, first
lea ebx, second
call swap
...
swap: proc
mov temp, [eax]
mov [eax], [ebx]
mov [ebx], temp
ret
swap: endp
Problem
If you have more than three parameters is is better to use the stack to avoid running out of registers.
Example
Call a procedure to multiple top 2 values on stack, leaving result in eax
.
push num1 ; put first num on stack
push num2 ; put second num on stack
call multiply
mov result, eax ; store result
...
multiply: proc
pop ebx ; save return address
pop eax ; pop a value from stack to eax
mov tmp, eax ; store this value
pop eax ; pop next value from the stack
mul eax, tmp ; multiply the two values
push ebx ; put ret address back on stack
ret
multiply: endp
We must save the return address from the top of the stack when we use the stack for procedures.