Next: Functions
Up: Parameter Passing for Subroutines
Previous: Invoking Subroutines with Parameters
Contents
The allowance of nested invocation is what makes structured programming
languages (like Pascal, C and others) powerful. You can invoke a subroutine
from a subroutine. There is no theoretical limitation as to how many
levels of invocations a program can nest.
Parameter passing in nested invocation requires some additional
explanation. This is especially the case with passing by reference.
Let us consider the following program:
var gx, gy : integer;
procedure sub1(x1 : integer; var y1 : integer);
begin
y1 := y1 + x1
end;
procedure sub2(var x2 : integer; var y2 : integer);
begin
x2 := x2 * 2;
sub1(x2, y2)
end;
begin
gx := 6;
gy := 11;
sub2(gx, gy)
end.
Let's see what happens when this program executes:
- gx and gy are initialized to 6 and 11,
respectively.
- sub2 is invoked, x2 becomes a reference to
gx, y2 becomes a reference to gy.
- x2 is doubled. Since x2 is a reference to
gx, the value of gx is doubled from 6 to 12.
- sub1 is invoked, the value of x2 is passed by
value of x1 of sub1, which means x1
has a copy of the value of x2. What is x2?
x2 is a reference to gx. As a result,
formal parameter x1 of sub1 has a value of
12. y2 is passed by reference to y1.
y2 is a reference to gy. This means
y1 is also a reference to gy.
- we add x1 to y1. x1 has a value of
12. y1 is a reference to gy, which has a value
of 11. The sum is 23, and it is stored to y1. Since
y1 is a reference to gy, 23 is actually
store to gy!
- we now return from sub1.
- we now return from sub2.
- in the main program gx has a value of 12, and gy
has a value of 23.
What if we change formal parameter y2 from passed-by-reference
to passed-by-value? It becomes a snapshot of the value of gy,
but changes to y2 is no longer reflected in gy. When we
pass y2 by reference to y1 of sub1, we make
y1 a reference to y2 instead of gy.
This means the outcome of the program is that gx still has a
value of 12, but gy has a value of 11 instead of 23 because
changes to y1 in sub1 changes y2, which is
only a copy of gy, leaving gy unmodified.
Next: Functions
Up: Parameter Passing for Subroutines
Previous: Invoking Subroutines with Parameters
Contents
Tak Auyeung
2003-12-03