Skip to content
Official PYQ · 1987

GATE CS 1987 Q1-xx — Runtime Environments

Explain with AI

For the program given below what will be printed by the write statements marked (1)(1) and (2)(2) 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.
Choose one option
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:

  1. Main Block:
    • Global variables x and y are allocated.
    • x := 7 and y := 8.
    • Procedure Q is called.
  2. Inside Procedure Q:
    • Local variables x and y are allocated.
    • x := 3 and y := 4.
    • Procedure P(y) is called with argument y = 4 (so parameter n = 4).
  3. Inside Procedure P:
    • The active call sequence is: Main → Q → P.
    • The variable x inside P is free. Under dynamic scoping, it refers to the most recently declared active x, which is the local variable x of Q.
    • The assignment is computed as: x:=n+2n−3=4+24−3=6x := \frac{n + 2}{n - 3} = \frac{4 + 2}{4 - 3} = 6
    • Thus, the local variable x of Q is updated to 66.
  4. Back in Q:
    • The statement Write(x) marked as (1)(1) is executed.
    • Since the local x of Q was updated to 66, it prints 66.
  5. Back in Main Block:
    • Procedure Q finishes execution, and its local variables are deallocated.
    • The statement Write(x) marked as (2)(2) is executed.
    • Here, x refers to the global variable x, which remains unchanged at 77.

Therefore, the printed values are 6,76, 7, which corresponds to Option B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Runtime Environments questions