4.3 Local variables in a recursive subroutine

Recursion works very well with local variables because local variables are also allocated on a per-invocation basis. This means that in the case of recursion, each invocation of a recursive subroutine allocates its own columns for the local variables. When we execute code, only the rightmost columns labeled with the name of a local variable are used.

This can take some getting use to. Let us observe a fairly useless sample program.


Listing 7: Recursive subroutine with a local variable
1define sub s1 
2  local x 
3  xy 
4  if x>then 
5    yy-
6    invoke s1 
7  end if 
8end define sub 
9y
10invoke s1

This pseudocode generates the following trace:










traceA
B
CD EF G

explanation










comments
line#
y










pre
?










9
2










10 retline# x










post ?










3
2

Nothing new here!










(x¿1) is T 4










5
1










6 retline# x










8
?

There are two points to note here. First, the return line number is 8 because line 8 logically follows line 6 (we do not trace “end if”). More importantly, at this point, we have two columns labeled “x”, and both are the same local variable of the same subroutine. However, there is no confusion because only the rightmost column is accessible. In other words, only local variables created by the latest invocation is accessible.










3
1










(x¿1) is F 4










8 retline#x










8 retline#x










post