Skip to content
Official PYQ · 1987

GATE CS 1987 Q1-xix — Runtime Environments

Explain with AI

Study the following program written in a block-structured language:

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.

What will be printed by the write statements marked (1)(1) and (2)(2) in the program if the variables are statically scoped?

Choose one option
View worked solution

Answer: A

Under static (lexical) scoping, a variable reference is resolved in the block in which the procedure is defined, rather than where it is called.

Let's trace the execution step-by-step:

  1. Main Program Execution:
    • The global variables are initialized: global x=7\text{global } x = 7 and global y=8\text{global } y = 8.
    • Procedure QQ is called.
  2. Inside Procedure QQ:
    • QQ declares its own local variables xx and yy.
    • Local x=3x = 3 and local y=4y = 4.
    • QQ calls P(y)P(y) with the argument n=4n = 4.
  3. Inside Procedure P(n)P(n):
    • PP is defined at the global level, so any non-local variable reference in PP resolves to the global scope.
    • The assignment is: x=(n+2)/(n−3)x = (n + 2) / (n - 3).
    • With n=4n = 4, we get: global x=(4+2)/(4−3)=6/1=6\text{global } x = (4 + 2) / (4 - 3) = 6 / 1 = 6.
  4. Returning to QQ:
    • The statement Write(x) at (1) refers to QQ's local variable xx, which is still 33. Thus, 33 is printed.
  5. Returning to Main Program:
    • The statement Write(x) at (2) refers to the global variable xx, which was updated to 66 by procedure PP. Thus, 66 is printed.

Therefore, the values printed are 3,63, 6.

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

Published
Report a correction
Keep exploringMore Runtime Environments questions