The Gateway to Computer Science Excellence
+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.

in Programming by Veteran
retagged by | 558 views

1 Answer

+6 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$.

by Veteran
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 :)

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
52,217 questions
59,949 answers
118,171 users