GATE Computer ScienceHardGATE CS (PYQ pattern)

int x = 1; int g() { x = x + 1; return x; } int f(int n) { int x = n; if (n == 0) return g(); int r = f(n − 1); return r + g(); } What does f(3) return under static scoping and under dynamic scoping?

  1. A. 14 and 6
  2. B. 10 and 14
  3. C. 14 and 10
  4. D. 9 and 10

Correct answer: C. 14 and 10

Static: g always increments the global x: f(0) gets 2, f(1) = 2 + 3 = 5, f(2) = 5 + 4 = 9, f(3) = 9 + 5 = 14. Dynamic: g increments the x of the f that called it: f(0): 0 → 1, returns 1; f(1): 1 + (1 → 2) = 3; f(2): 3 + 3 = 6; f(3): 6 + 4 = 10 (the global x stays 1).

More Compiler Design questions

Exams that ask this topic