For the program given below what will be printed by the write statements marked and in the program if the variables are dynamically scoped?
Var x, y:interger;
procedure P(n:interger);
begin
x := (n+2)/(n-3);
end;
procedure Q
Var x, y:interger;
begin
x:=3;
y:=4;
P(y);
Write(x); __(1)
end;
begin
x:=7;
y:=8;
Q;
Write(x); __(2)
end.View worked solution
Answer: B
Under dynamic scoping, a free variable in a procedure refers to the most recently declared active variable with that name in the execution call stack.
Step-by-Step Execution Trace:
-
Main Block:
- Global variables
xandyare allocated. x := 7andy := 8.- Procedure
Qis called.
- Global variables
-
Inside Procedure
Q:- Local variables
xandyare allocated. x := 3andy := 4.- Procedure
P(y)is called with argumenty = 4(so parametern = 4).
- Local variables
-
Inside Procedure
P:- The active call sequence is:
Main → Q → P. - The variable
xinsidePis free. Under dynamic scoping, it refers to the most recently declared activex, which is the local variablexofQ. - The assignment is computed as:
- Thus, the local variable
xofQis updated to .
- The active call sequence is:
-
Back in
Q:- The statement
Write(x)marked as is executed. - Since the local
xofQwas updated to , it prints .
- The statement
-
Back in Main Block:
- Procedure
Qfinishes execution, and its local variables are deallocated. - The statement
Write(x)marked as is executed. - Here,
xrefers to the global variablex, which remains unchanged at .
- Procedure
Therefore, the printed values are , which corresponds to Option B.
Free practice · Your answers on this page are not saved.
