Variable parameters
 

Variable parameters
Procedures can also be implemented to change the value of original variables which are accepted by the procedure. To illustrate this, we will develop a little procedure called swap. This procedure accepts two integer values, swapping them over.

Previous procedures which accept value parameters cannot do this, as they only work with a copy of the original values. To force the procedure to use variable parameters, preceed the declaration of the variables (inside the parenthesis after the function name) with the keyword var.

This has the effect of using the original variables, rather than a copy of them.


program Variable_Parameters (output);

procedure SWAP ( var value1, value2 : integer );
var temp : integer;
begin
temp := value1;
value1 := value2; {value1 is actually number1}
value2 := temp {value2 is actually number2}
end;

var number1, number2 : integer;
begin
number1 := 10;
number2 := 33;
writeln( 'Number1 = ', number1,' Number2 = ', number2 );
SWAP( number1, number2 );
writeln( 'Number1 = ', number1,' Number2 = ', number2 )
end.

When this program is run, it prints out

Number1 = 10 Number2 = 33
Number1 = 33 Number2 = 10




SELF TEST
Why is the following procedure declaration incorrect?

procedure Wrong ( A : integer; var B : integer );
var A : integer; B : real;

(c) Shilpa Sayura Foundation 2006-2017