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(inout, output);
var a, b:integer;
procedure P(x, y, z:integer);
begin
y:=y+1
z:=x+x
end P;
begin
a:=2; b:=3;
p(a+b, a, a);
Write(a)
end.
View worked solution
Answer: 10
To find the output of the program under the call-by-reference parameter passing method, we trace the execution step-by-step:
1. Initial State
Before calling procedure P, the variables in the main program are initialized as:
a = 2b = 3
2. Parameter Binding in Call-by-Reference
The procedure call is p(a+b, a, a) with formal parameters (x, y, z):
- For expression
a+b: Since an expression does not have an l-value (memory address), the compiler evaluates the expression at the time of the call, stores the result in a temporary location, and passes the reference of this temporary location tox.
Thus,xreferencestemp(value is ). - For variable
a: Bothyandzreceive the reference (address) of the variablea. This creates an alias, meaning any modification toyorzdirectly affectsa.
3. Execution of Procedure P
-
Statement 1:
y := y + 1Since
yreferencesa, this is equivalent to: -
Statement 2:
z := x + xSince
zreferencesaandxreferencestemp(which holds ):
4. Output
After returning from the procedure, the main program executes Write(a). The value of a is now 10.
Free practice · Your answers on this page are not saved.
