Home Up Contents Search

Parameter Passing

Parameter Passing

Procedures and functions can declare two types of parameters: reference parameters (those preceded by the VAR reserved word) and value parameters (those without VAR).

When a value parameter is passed at runtime, a copy of the parameter--not the parameter itself--is placed on the stack. In effect, this copy becomes a local variable of the called routine. As a local copy, the procedure can assign to it without affecting the original variable in the calling routine.

In contrast, when a reference (VAR) parameter is passed to a procedure, the address of the parameter is placed on the stack. This means that assigning to the variable in the called procedure or function affects the caller's variable. Only variables (not constants or expressions) can be passed as reference parameters--because only variables have addresses in memory.

Stack size constraints can make it advantageous to pass variables by reference, even when you don't intend to change a parameter in the called routine. For example, it takes 10K of stack space to pass a 10K array by value, but only 4 bytes to pass it by reference.


program ParameterDemo1;
type t = array [1..5000] of char;

procedure ByValueProc(a: t);
begin

a[2500] := 'F';

end; { ByValueProc }

procedure ByReferenceProc(VAR a: t);
begin

a[2500] := 'F';

end; { ByReferenceProc }

var AnArray: t;

begin { ParameterDemo1 }

ByValueProc(AnArray);
Writeln(AnArray[2500]);
ByReferenceProc(AnArray);
Writeln(AnArray[2500]);

end. { ParameterDemo1 }




program ParameterDemo2;
var A : integer;

procedure Proc1(N : integer);
begin

N := 55;

end; { Proc1 }

procedure Proc2(var N : integer);
begin

N := 33;

end; { Proc2 }


var G : integer;

begin { ParameterDemo2 }

G := 22;
Proc1(G);
Writeln(G);
Proc2(G);
Writeln(G);
Proc2(55);
{ This line won't compile, because you can't pass constants as var parameters }

end. { ParameterDemo2 }

 
Previous
Send mail to ljschwerin@hotmail.com with questions or comments about this web site.

Copyright © 1999-2002 Leon Schwerin
Last modified: 26 March 2000
1