In: Computer Science
(4 pts) What does the function fun print if the language uses static scoping? What does it print with dynamic scoping?
x: integer <-- global procedure
Assignx(n:integer)
x:= n
proc printx
write_integer(x)
proc foo
Assignx(1)
printx
procedure boo
x: integer
Assignx(2)
printx
Assignx(0)
foo()
printx boo()
printx
Answer;
For static scoping:
It will print:
1
1
2
2
Explanation:
First Assignx sets global x as 0.
Outputs:
Line 1: foo() is called which assign 1 to the global x and then prints it i.e. 1
Line2: printx is called which prints the global x which was set to 2 in the previous step
Line3: boo() is called which assigns 2 to the global x by calling Assignx and then prints it i.e. 2
Line 4: printx is called which prints the global x which was set to 2 in the previous step
For dynamic scoping: (function call stack is checked for latest scope)
It will print:
1
1
2
1
First Assignx(0) sets global x since no function is called yet
Outputs:
Line 1: foo() is called and assigns 1 to global x and prints it as no other local x are declared in it.
Line 2: printx is called with global x
Line 3: boo() is called and it has local x declared, so latest scope of x is that inside boo()'s. So boo() calls assignx and sets its local x to 2 and then calls printx with this same x for printing it.
Line 4: finally printx is called with global x's scope which prints 1 as it was set in line 2
Thanking you...