GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 18(b)

Trace dynamic scope and reference parameters

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2000 paper

GATE 2000, Q18(b) Descriptive
Report issue

Scope, Lifetime & Storage Classes

Question 18(b), GATE 2000: Pseudo-Pascal: global x; Q(z) does z:=z+x; writeln(z). P(y) declares local x, does x:=y+2; Q(x); writeln(x). Main does x:=5; P(x); Q(x); writeln(x). Q and P are siblings declared in main. Find output under call-by-reference and dynamic scoping.
Question 18(b), GATE 2000: Pseudo-Pascal: global x; Q(z) does z:=z+x; writeln(z). P(y) declares local x, does x:=y+2; Q(x); writeln(x). Main does x:=5; P(x); Q(x); writeln(x). Q and P are siblings declared in main. Find output under call-by-reference and dynamic scoping.
Tap to enlarge
Answer & solution

Answer: 14 14 10 10 (no official key was published)

Main’s x starts at 5. In P(x), y aliases main’s x, but P also owns a distinct local x. It reads y=5 and assigns local x=7. Q(x) is then called with a reference to that local x, so z aliases P.x. Under dynamic scoping, Q’s free x resolves to the nearest active caller with an x, also P.x. The assignment z:=z+x therefore reads 7+7 and writes 14 into P.x. Q prints 14, and P’s next writeln(x) prints the same 14. Main’s global x is still 5 because neither assignment changed y or main.x. After P returns, main calls Q(x); now both reference parameter z and dynamically resolved x refer to main.x. Their old values are 5, so the assignment writes 10 into main.x. Q prints 10 and main’s final writeln(x) also prints 10. Aliasing and name resolution are separate steps: first identify each referenced storage cell, then evaluate the addition using its pre-assignment value.

Original paper, page 9