Problem: write a procedure that swaps the values of two variables.
The peculiarities of this task are that we need the changes made in the procedure to become known to the calling program.
Let's try to write the procedure like this:
var x, y: integer;
procedure Swap(a, b: integer); // with such a description of the procedure parameters,
var c: integer;
begin // will copy the values of the arguments (x and y)
// variables a and b are independent variables not related to x and y
c := a;
a := b;
b := c;
end;
begin
x := 1;
y := 2;
Swap(x, y); //values of variables x and y (arguments) are copied into parameters a and b
writeln('x = ', x, ', y = ', y); // x=1, y=2
end.
If you run this program, you can see that the values of the variables
x and
y have not changed. In order for the parameters to change the values of the arguments, you must use
passing data by reference. To do this, after the name of the data type in the header of the subroutine, you must put the word
var
procedure Swap(var a, b: integer); // now variables a and b get addresses of variables x and y in memory
var c: integer;
begin
c := a;
a := b;
b := c;
end;
Usage: If you pass an argument by reference, then only the variable name (
NOT a number and NOT an arithmetic expression) can be in this place when calling the procedure!
DO NOT call a procedure like this:
Swap(x, 4);
Swap(5+x, y);