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); }Answer: D. 4, 4 — ConceptUnder call-by-reference, a formal parameter aliases the caller’s variable, so an assignment through the parameter updates the same storage. Under…
- A.
6, 2
- B.
6, 6
- C.
4, 2
- D.
4, 4
Attempted by 120 students.
Show answer & explanation
Correct answer: D
Concept
Under call-by-reference, a formal parameter aliases the caller’s variable, so an assignment through the parameter updates the same storage. Under dynamic scoping, a free name is resolved to the nearest active binding with that name in the call stack.
Application
Initially, the global variable a has value 3. In m(a), the formal y is a reference to that global variable.
The local a in m is set to 1. Then a = y - a gives a = 3 - 1 = 2, while y still refers to the global a.
The call n(a) passes m’s local a by reference, so x in n aliases that local variable.
Inside n, dynamic scoping resolves the free name a to m’s active local a. Therefore x = x * a evaluates as 2 * 2 and stores 4 in the same local variable.
The print in n outputs 4. After n returns, m prints its local a, which is the same updated storage, so it also outputs 4.
Cross-check
Because x and m’s local a are aliases during n, both must contain the same value after x is assigned. Hence the two printed values cannot differ.
Result
The output is 4, 4.