What's the difference between static and dynamic scoping in this exercise?
-
06-12-2019 - |
Frage
I get confused when dealing with the static scope and dynamic scope, and for this pseudocode I have to find both. For both I believe it should print out: 9 4 2 3 however, I'm not entirely sure. Any help would be appreciated, thanks.
g: integer
procedure B(a: integer)
x: integer
x := a X a
R(1)
procedure A(n: integer)
g := n
procedure R(m: integer)
write_integer(x)
x /:= 2 -- integer division
if x > 1
R(m + 1)
else
A(m)
procedure main() -- entry point
B(3)
write_integer(g)
Lösung
If your language were statically scoped, then the variable x
would be local only to the function B
, and it would not be visible outside B
.
However, your language is dynamically scoped: The first time the control flow passes over the line x: integer
, the variable x
is now globally accessible.
So, here's the order of events:
B(3)
assignsx := 9
R(1)
writes9
and assignsx = 4
and callsR(2)
R(2)
writes4
and assignsx = 2
and callsR(3)
R(3)
writes2
and assignxx = 1
and callsA(3)
A(3)
assignsg = 3
write_integer(g)
prints3
.