GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 18(a)

Trace static scope and value parameters

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

GATE 2000, Q18(a) Descriptive
Report issue

Scope, Lifetime & Storage Classes

Question 18(a), 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-value and static scoping.
Question 18(a), 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-value and static scoping.
Tap to enlarge
Answer & solution

Answer: 12 7 10 5 (no official key was published)

Main sets global x=5. P receives a separate value parameter y=5 and sets its local x=y+2=7. P calls Q(x), so Q receives a separate z=7. Static scoping resolves Q’s free x through its lexical declaration environment, main, not through the caller P: that x is the global 5. Therefore Q sets its own z=7+5=12 and prints 12. Because z was passed by value, P’s local x remains 7, so P next prints 7. Returning to main leaves global x=5. Main’s Q(x) receives z=5 and uses global x=5, so it prints 10; this changes only z. Finally main prints global x=5. The four outputs, one per writeln, are 12,7,10,5. Do not let P’s local x affect a statically scoped sibling procedure.

Original paper, page 9