5.2 Byval parameter in a recursive subroutine

Because a byval parameter is essentially a local variable with an initial value determined by an invoke statement, it can also be utilized in recursion. However, this can be a little confusion sometimes. Let us examine the following pseudocode.


Listing 9: Using a byval parameter in recursion
1define sub s1 
2  byval x 
3  if (x> 0) then 
4    invoke s1 (x-1)x 
5  end if 
6end define sub 
7invoke s1 2x

This pseudocode results in the following trace.











trace
A
B
C DE FG H

explanation











1comments
line#











2 7retline#x

This is the first invocation, it is clear why parameter “x” has an initial value of 2.











3
post
2











4(x > 0) is T 3











5 4 retline#x











6
6
1

This is the second invocation of “s1”. On line 4 of the pseudocode, (x - 1) uses the parameter that is already defined (column D), whereas x (to the right of the right arrow) refers to the parameter that is being set up (column F).











7(x > 0) is T 3











8 4 retline#x











9
6
0

At this point, we have three invocations of “s1” stacked up. Because each invocation has its own parameter “x”, we have three of them.











10(x > 0) is F 3











11 6 retline#x











12 6 retline#x











13 6retline#x











14
post