Consider the following program
Program P2
var n : int;
procedure W(var x : int)
begin
x = x + 1;
print x;
end
procedure D
begin
var n : int;
n = 3;
W(n);
end
begin \\begin P2
n=10;
D;
end
If the language has dynamic scooping and parameters are passed by reference, what will be printed by the program?
View worked solution
Answer: D
To find the output of the program, let's trace its execution step-by-step:
- Main Program Execution:
- The global variable
nis assigned the value10. - Procedure
Dis called.
- The global variable
- Inside Procedure
D:- A local variable
nis declared, which shadows the globaln. - This local
nis assigned the value3. - Procedure
W(n)is called, passing the local variablenas an argument.
- A local variable
- Inside Procedure
W:- Since parameters are passed by reference, the formal parameter
xbecomes an alias (reference) to the local variablenof procedureD. - The statement
x = x + 1increments the value of the referenced variable (localnofD) from3to4. - The statement
print xprints the current value ofx, which is4.
- Since parameters are passed by reference, the formal parameter
Note on Scoping: Dynamic scoping determines how non-local (free) variables are resolved by searching the activation stack. Since procedure W only accesses its local parameter x and does not use any non-local variables, the choice of dynamic scoping versus static scoping does not affect the output here.
Since the program prints 4, which is not present in options A, B, or C, the correct option is D.
Free practice · Your answers on this page are not saved.
