+1 vote
405 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.

retagged | 405 views

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

edited by
+1
Sir, why not ans = 2 5 5 in the dynamic scoping ??

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

1
2
+1 vote