Similar questions 2 more →
Functions & Parameter Passing


Answer & solution
Answer: 110. (no official key was published)
Step through it (11 steps)
The main program calls recur(z), so its reference parameter x is another name for the global variable z. Passing that reference onward as recur(x) keeps the same alias in every activation. There are not separate saved integer values of x in the suspended calls.
Initially x=z=10. The first body executes x:=x+z, doubling the shared variable to 20. The next call doubles it to 40. Because the guard is x≤40, the call seeing 40 also executes the body and doubles it to 80. The next call sees 80 and returns immediately. Thus four activations exist, three with a pending final assignment.
On unwinding, every z:=x+10 reads the current shared value, because x aliases z. The three pending assignments make the values 80→90→100→110. The program consequently prints 110.
It would be incorrect to use the descent values 10,20,40 as saved local copies during unwinding: that is pass-by-value behavior. It would also be incorrect to stop at 80, since the three assignments following recursive calls still have to execute. The example shows why mutation of a reference argument can interact unexpectedly with a global variable naming the same storage location.