Question

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); }
Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2016 answer key
Note on this question

Reference book mistakenly labels option C as correct despite deriving 4 and 4 in its steps.

Solution

Trace dynamic scope lookups along the active call stack with pass-by-reference aliases.

Under dynamic scoping, a non-local variable reference is resolved by searching back through the chain of active function calls (the call stack) until a declaration of that variable name is found. Pass-by-reference means formal parameters are bound directly to the memory location of the actual arguments.

Trace execution:

  1. Global declaration: a = 3.
  1. main() calls m(a):
    • In m(y), formal parameter y is passed by reference to a (which is global a).
    • Inside m(), a = 1; introduces/binds local variable a in m's frame with value 1.
    • Next, a = y - a; evaluates: y refers to global a = 3, and local a = 1. Thus, local a becomes 3−1=23 - 1 = 2.
  1. m() calls n(a):
    • Formal parameter x of n is passed by reference to m's local variable a.
    • Inside n(x): x = x * a;
      Under dynamic scoping, looking up a in the caller's stack frame resolves to m's local variable a (value 2).
      Since x is also an alias for m's local a, both x and a refer to the same location!
      Thus, x=2×2=4x = 2 \times 2 = 4, updating m's local a to 4.
    • print(x); in n prints 4.
  1. Control returns to m():
    • print(a); in m prints m's local a, which now holds 4.
      Both print calls output 4, yielding 4, 4.
Final answer

D

Common trap

Assuming static (lexical) scoping where n would resolve a to global a = 3, which would yield x=2×3=6x = 2 \times 3 = 6 and output 6, 2.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2016 Computer Science and Information Technology (CS) Session 1
Question
46 of 65, printed as CS Q.36
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.