recategorized by
7,240 views
25 votes
25 votes

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)$ and $(2)$ in the program if the variables are statically scoped?

  1. $3, 6$
  2. $6, 7$
  3. $3, 7$
  4. None of the above.
recategorized by

2 Answers

Best answer
44 votes
44 votes

Using Static Scoping:
First, procedure Q is called from the main procedure. Q has local variables x and y with values 3 and 4 respectively. This local variable y (value 4) is being passed to procedure P during call, and received in local variable n inside procedure P. Now, as P does not have any local definition for variable x, it will assign the evaluated value of (n+2)/(n-3) i.e. (4+2)/(4-3)=6 to the global variable x, which was previously 7. After the call of procedure P, procedure Q writes the value of local variable x which is still 3. Lastly, the main procedure writes the value of global variable x which has been changed to 6 inside procedure P. So, the output will be 3, 6.

Using Dynamic Scoping:
The same sequence of statements will be executed using dynamic scoping. However, as there is no local definition of variable x in procedure P, it will consider the recent definition in the calling sequence; as P is being called from procedure Q, definition of x from Q will be used, and value of x will be changed to 6 from 3. Now, when Q writes local variable x, 6 will be printed. The write global variable x from main procedure will print 7 (as value of the global variable x has not been changed). So, the output will be 6, 7.

Correct Answer: $A$

edited by
18 votes
18 votes

 

In static scoping, the free variable is replaced by the global variable, which means if a variable is not defined locally it will take the value from a global variable.

So option (A) is correct.

edited by
Answer:

Related questions

15 votes
15 votes
2 answers
2
makhdoom ghaya asked Nov 8, 2016
4,944 views
Using longer identifiers in a program will necessarily lead to:Somewhat slower compilationA program that is easier to understandAn incorrect programNone of the above
16 votes
16 votes
4 answers
3
makhdoom ghaya asked Nov 8, 2016
3,593 views
An operator precedence parser is aBottom-up parser.Top-down parser.Back tracking parser.None of the above.
16 votes
16 votes
2 answers
4
makhdoom ghaya asked Nov 8, 2016
6,323 views
In a compiler the module that checks every character of the source text is called:The code generator.The code optimiser.The lexical analyser.The syntax analyser.