GATE CSE
First time here? Checkout the FAQ!
x
+1 vote
258 views

Consider the program below:

Program main:
    var r:integer;
    procedure two:
        begin write (r); end
    procedure one:
        var r:integer;
        begin r:=5; two; end
    begin r:=2;
        two; one; two;
    end

What is printed by the above program if

  1. Static scoping is assumed for all variables;
  2. Dynamic scoping is assumed for all variables.

Give reasons for your answer.

 

asked in Programming by Veteran (64.6k points)  
retagged by | 258 views

1 Answer

+4 votes
Best answer

In static scoping all variables are assigned scope before the program execution. If a variable declaration is missing in local scope it is checked in global scope. So, here the output will be 

2 2 2 

as the $r$ is procedure 2 is always the global $r$.

In dynamic scoping, non local variables are assigned scope during program execution. If a variable declaration is missing in local scope, it is checked in the function which called the current one. So, the output will be

2 5 2

as when procedure $one$ calls procedure $two$, $r$ will be from procedure $one$ and it has value $5$.

answered by Veteran (294k points)  
edited by
Sir, why not ans = 2 5 5 in the dynamic scoping ??

Since 'var r' in 'procedure one' is local variable  right ??
Yes, that was a typo. Thanks :)


Top Users Sep 2017
  1. Habibkhan

    6836 Points

  2. Arjun

    2310 Points

  3. Warrior

    2306 Points

  4. rishu_darkshadow

    2076 Points

  5. A_i_$_h

    2004 Points

  6. nikunj

    1980 Points

  7. manu00x

    1750 Points

  8. Bikram

    1744 Points

  9. SiddharthMahapatra

    1718 Points

  10. makhdoom ghaya

    1690 Points


26,038 questions
33,649 answers
79,695 comments
31,069 users