I am having trouble understanding the answer to a homework we got back. I believe I am getting confused on the concepts of functions being "nested", but maybe that is wrong. I am looking for some help in regards to following the assignment of dynamic and static scoping values from the following code.
x : integer -- global
procedure set_x(n : integer)
x := n
end
procedure print_x
write_integer(x)
end
procedure first
set_x(1)
print_x
end
procedure second
x : integer
set_x(2)
print_x
end
// program starts here
set_x(0)
first()
print_x
second()
print_x
Static Scoping Output: 1122
Dynamic Scoping Output: 1121
My thoughts as I go through each one:
Static:
- Run
set_x(0), this makes a local variable due to the parameter of n, but since we set x to n without declaring x locally (int x =..) we then update the global x to 0. - Run
first(), which doesset_x(1), which following the same logic updates x to 1 globally. we then runprint_xwithin first which prints the global x of 1. - Run
print_x, which just re-prints 1. - Run
second()we locally declare x and runset_x(2), which goes updates 2 to n. (because of theset, not thesecondprocedure, right? We then run itsprint_xprocedure which prints the 2. - Run
print_xwhich again just dumps out the 2. - Resulting in 1122
Dynamic (more confused on this one)
- Run
set_x(0)which sets the x and global x to 0. - Run
first()we hitset_xagain and update x to 1. We print 1. - Run
print_xWe re-print 1. - Run
second()We locally make x, we runset_x(2), and set global x to 2. We then print 2. - Run
print_xFinally we re-print again and here is where I guessed 2, but the answer should 1. - My guess 1122, actual answer is 1121
I am confused on that last part of the dynamic and why it is a 1, and not a 2.