What will be the output of the following pseudo-code when parameters are passed by reference (modeled as copy-restore: on return, the final value of the formal parameter is copied back into the actual argument) 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);}- A6, 2
- B6, 6
- C4, 2
- 4, 4
Explanation
m(a) called: y is a LOCAL copy of a's value (3) — not a true alias, since 'pass by reference' here behaves as copy-restore, propagating back only when m returns. Inside m: a=1 sets the GLOBAL a to 1 (y is unaffected, still 3, since 'a' the free variable resolves via dynamic scoping to the global, distinct from local y). a=y−a: reads y(3, unchanged) minus GLOBAL a(1) = 2 → global a becomes 2. n(a) is called with the current global a(2), passed similarly as a local copy x=2 inside n. Inside n: x=x*a — 'a' resolves dynamically to the global, still 2 — x=2*2=4 (local to n only). print(x) prints 4. When n returns, x's final value (4) is copied back into the actual argument slot it was called with (the global a) — global a becomes 4. Back in m: print(a) reads the now-updated global a=4, printing 4. Output: 4, 4.
Source: GATE CS 2016 (Session 1 / Set A) (2016)
This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.