685 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
retagged | 685 views
0
is a is the answer ??
0

@Tendua,

is a is the answer ??

NO

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: $B$

edited

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

edited
6,7  in dynamic scoping newest  upcoming variable is selected

1