The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+1 vote

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;

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 (67.5k points)
retagged by | 284 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 (326k 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 :)

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

28,946 questions
36,792 answers
34,689 users