next up previous contents
Next: Functions Up: Parameter Passing for Subroutines Previous: Invoking Subroutines with Parameters   Contents

Nested Invocation

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:

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 up previous contents
Next: Functions Up: Parameter Passing for Subroutines Previous: Invoking Subroutines with Parameters   Contents
Tak Auyeung 2003-12-03