The GATE Grind

GATE 2016 CS – Question 46

Programming and Data Structures · Programming in C · 2 marks · Multiple choice

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);}
  1. 6, 2
  2. 6, 6
  3. 4, 2
  4. 4, 4

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (D) 4, 4

Explanation

Following the official key, `y` holds 3 when `m` is called. Inside `m`, `a = 1` and then `a = y - a = 3 - 1 = 2`. Then `n(a)` is called with `x` referring to `a`, so `x = x * a = 2 * 2 = 4`, and `print(x)` shows 4. Because `x` is a reference to `a`, `a` is now 4 as well, and `print(a)` in `m` also shows 4.