What will be the output of the following pseudo-code when parameters are…
2016
What will be the output of the following pseudo-code when parameters are passed by reference and dynamic scoping is assumed?
a = 3;
void n(x) { x = x * a; print (x); }
void m(y) { a = 1 ; a = y - a; n(a); print (a); }
void main () { m(a); }
- A.
6, 2
- B.
6, 6
- C.
4, 2
- D.
4, 4
Attempted by 104 students.
Show answer & explanation
Correct answer: D
Answer: 4, 4
Reasoning (step-by-step):
Start: global a = 3.
Call m(a): the actual parameter is the variable named a. Because parameters are passed by reference, the formal parameter y becomes an alias to that variable.
Inside m, the assignment a = 1 creates/uses a local binding of a in m (this local a shadows the global a under the function's activation). That local a is set to 1.
Next statement a = y - a computes using y (which aliases the original/global a with value 3) minus the local a (1): 3 - 1 = 2. The local a in m is updated to 2.
Call n(a): the actual argument is the variable a in m (the local a). Since parameters are by reference, x inside n aliases m's local a.
Inside n, the expression x = x * a uses dynamic scoping to resolve a to the most recent binding named a on the call stack, which is the local a in m. Both x and a refer to the same storage (value 2), so x becomes 2 * 2 = 4. This updates the local a in m to 4.
n prints x which is 4. Returning to m, printing a prints the same local a (now 4).
Thus the output is: 4, 4.