Pascal Programs:
Pass-By-Value:
The output will beprogram Pass(input, output);
var c, d : integer;procedure swap(a, b: integer);
var temp : integer;
begin{swap}
temp := a;writeln('Beginning of subprogram:');a := b;
writeln('a = ' , a );
writeln('b = ' , b );
b := temp;writeln('Ending of subprogram:');end; {swap}
writeln('a = ' , a );
writeln('b = ' , b );begin{program}
c := 1;
d := 0;writeln('Before call:');swap(c, d);
writeln('c = ' , c );
writeln('d = ' , d );writeln('After call:');end. {program}
writeln('c = ' , c );
writeln('d = ' , d );
Before call:Pass-By-Reference:
c = 1
d = 0
Beginning of subprogram:
a = 1
b = 0
Ending of subprogram:
a = 0
b = 1
After call:
c = 1
d = 0
The output will beprogram Pass(input, output);
var c, d : integer;procedure swap(var a, b: integer);
var temp : integer;
begin{swap}
temp := a;writeln('Beginning of subprogram:');a := b;
writeln('a = ' , a );
writeln('b = ' , b );
b := temp;writeln('Ending of subprogram:');end; {swap}
writeln('a = ' , a );
writeln('b = ' , b );begin{program}
c := 1;
d := 0;writeln('Before call:');swap(c, d);
writeln('c = ' , c );
writeln('d = ' , d );writeln('After call:');end. {program}
writeln('c = ' , c );
writeln('d = ' , d );
Before call:Pass-By-Reference with List:
c = 1
d = 0
Beginning of subprogram:
a = 1
b = 0
Ending of subprogram:
a = 0
b = 1
After call:
c = 0
d = 1
program Pass(input, output);Before call:
type SmallArray = array[1..5] of integer;
var list : SmallArray;
i, j : integer;procedure swap(var a, b: integer);
var temp : integer;
begin{swap}
temp := a;writeln('Beginning of subprogram:');a := b;
writeln('a = ' , a );
writeln('b = ' , b );
b := temp;writeln('Ending of subprogram:');end; {swap}
writeln('a = ' , a );
writeln('b = ' , b );begin{program}
i := 3;
for j := 1 to 4 do
list[j] := j + 1;
list[5] := 0;writeln('Before call:');swap(i, list[i]);
writeln('i = ' , i );
writeln('list[i] = ' , list[i]);
writeln(list[1], list[2], list[3], list[4], list[5]);writeln('After call:');end. {program}
writeln('i = ' , i );
writeln('list[i] = ' , list[i]);
writeln(list[1], list[2], list[3], list[4], list[5]);
The address of list[i]
is computed at the time of the call and does
not change after that.
The parameter
of b in subprogram was referenced to the box of list[3]
at the time
when the main program called the subprogram.
After that,
the reference to which box is not changed.
Therefore,
the element in list[3] is changed to the new value of b.