4.2 Local variables of the same name (in different subroutines)

There is no problem if two subroutines use the same name for their local variables. This is because when we are executing the code of one subroutine, only local variables of that subroutine is visible, and therefore accessible. In the case there are multiple columns labeled the same name, and there is no error with the pseudocode, then the rightmost (most recent) column is used.

Here is an example to illustrate that.


Listing 6: Two subroutines containing local variables of the same name
1define sub s1 
2  local x 
3  x
4end define sub 
5define sub s2 
6  local x 
7  x 10 
8  invoke s1 
9  xx+2 
10end define sub 
11invoke s2







trace
A
B C D E

explanation








1
line#








2
pre

The “pre” condition is empty because we do not have any global variables!








3 11retline#x








4
post ?








5 7
10

On line 7, which is a part of “s2”, “x” refers to the local variable of “s2”.








6 8 retline#x








7
9
?

Here we allocate another column (E) and label it “x” for the invocation of “s1”.








8 3
2

Line 3 is a part of “s1”, which means “x” refers to the local variable “x” of “s1”. Furthermore, “x” refers to column E because it is the rightmost (most recently created) column that is labeled “x”. At this point, the local variable “x” of “s2” (column C) still exists, but “s1” has no access to that column because the scope of a local varaible is local to the subroutine.








9 4 retline#x








10 9
12








11 10 retline# x








12
post