retagged by
7,461 views
15 votes
15 votes

Consider the program below in a hypothetical programming language which allows global variables and a choice of static or dynamic scoping.

int i;
program main()
{
    i = 10;
    call f();
}

procedure f()
{   
    int i = 20;
    call g ();
}
procedure g()
{   
    print i;
}

Let $x$ be the value printed under static scoping and $y$ be the value printed under dynamic scoping. Then, $x$ and $y$ are:

  1. $x=10, y=20$
  2. $x=20, y=10$
  3. $x=10, y=10$
  4. $x=20, y=20$
retagged by

3 Answers

Best answer
30 votes
30 votes

In static scoping, the scope of an identifier is determined by its location in the code, and since that doesn't change, the scope doesn't either. In dynamic scoping, the scope is determined by the sequence of calls that has led to the use of an identifier, and since that can be different each time that use is reached, is dynamic.

So, here:

Option A must be the answer.

As, under static scoping$:x=10(\text{global}\; i)$

under dynamic scoping$:y=20($according to the sequence of calls,i.e $20)$

edited by
8 votes
8 votes
The answer should be (A) x = 10 and y = 20,

Since the value of x is based on static scoping, in the procedure g() print i will directly look into the global scope and find i = 10 which was previously set by main() and

Since the value of y is based on dynamic scopint, procedure g() will first look into the function which called it, i.e. procedure f() which has a local i = 20, which will be taken and 20 will be printed.
–2 votes
–2 votes
In main procedure value of i is 10

Now in static scoping when main is called global variable i becomes 10.

then f() called , global variable i value becomes 20

Now g() is called. g() has no local variable of it's own . So, it takes the value of global i , and prints i=20

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

Now in dynamic scoping main is called , global variable i becomes 10.

then f() called, but it won't change the value of global variable i .

Now g() called and here i is not declared, So, it takes the value from previous scope of f() , i.e. i=20

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

So, Ans C) 20,20
Answer:

Related questions

23 votes
23 votes
5 answers
3