What is printed by following program, assuming call-by-reference method of passing parameters for all variables in the parameter list of procedure P?
program Main(input, output);
var a, b : integer;
procedure P(x, y, z : integer);
begin
y := y + 1;
z := x + x
end;
begin
a := 2;
b := 3;
P(a, b, b);
writeln(a, b)
end.
A. a = 2, b = 3
B. a = 2, b = 4
C. a = 2, b = 7
D. a = 4, b = 4
GATE 1988 · Compiler Design · Parameter Passing · medium
Answer: The program prints a = 2, b = 4.
Bind parameters by reference: The call P(a, b, b) binds: x is an alias for a (value 2), y is an alias for b (value 3), z is also an alias for b (same location as y).
Execute y := y + 1: y and b refer to the same location. b was 3, so b := 3 + 1 = 4. Now b = 4.
Execute z := x + x: z refers to b, x refers to a. So b := a + a = 2 + 2 = 4. b is still 4 (coincidentally the same value).
Read printed output: writeln(a, b) prints a = 2, b = 4.