The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+8 votes
649 views

For the program given below what will be printed by the write statements marked (1) and (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.
  1. $3, 6$
  2. $6, 7$
  3. $3, 7$
  4. None of the above
asked in Compiler Design by Boss (41.1k points)
retagged by | 649 views
0
is a is the answer ??
0

@Tendua,

is a is the answer ??

NO

3 Answers

+3 votes
Best answer

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.

answered by Active (4k points)
selected by
+14 votes

In Dynamic Scoping free variable is replaced by previous function call value.

answered by Boss (13.9k points)
edited by
0 votes
6,7  in dynamic scoping newest  upcoming variable is selected
answered by (17 points)
Answer:

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,122 questions
53,242 answers
184,720 comments
70,482 users