GATE Computer ScienceHardGATE CS (PYQ pattern)

int x = 1; void p() { x = x + 10; } void r() { print(x); } void q() { int x = 5; p(); r(); } main() { q(); r(); print(x); } What is printed (three values in order) under static scoping and under dynamic scoping?

  1. A. static: 5 11 11; dynamic: 15 1 1
  2. B. static: 11 11 11; dynamic: 15 15 1
  3. C. static: 11 1 1; dynamic: 15 1 11
  4. D. static: 11 11 11; dynamic: 15 1 1

Correct answer: D. static: 11 11 11; dynamic: 15 1 1

Static: p and r always see the global x. p makes it 11; r inside q prints 11; r from main prints 11; main prints 11. Dynamic: called from q, p finds q's local x = 5 and makes it 15; r inside q prints 15. After q returns its x is gone, so r from main finds the global, still 1, and main prints 1.

More Compiler Design questions

Exams that ask this topic