GATE / CS ARCHIVE

GATE CSE 1991 / QUESTION 9(b.i)

Lexical scope selects declaration context

Compiler Design · Runtime Environments & Parameter Passing · Full GATE CSE 1991 paper

GATE 1991, Q9(b.i) Descriptive
Report issue

Runtime Environments & Parameter Passing

Question 9(b.i), GATE 1991: Global integers a,b; procedure P sets a:=5;b:=10. Procedure Q declares its own local integers a,b and calls P. Main sets global a:=1;b:=2, calls Q, then prints global a,b. Give output under static scope.
Question 9(b.i), GATE 1991: Global integers a,b; procedure P sets a:=5;b:=10. Procedure Q declares its own local integers a,b and calls P. Main sets global a:=1;b:=2, calls Q, then prints global a,b. Give output under static scope.
Tap to enlarge
Answer & solution

Answer: a=5,b=10. (no official key was published)

Under static, or lexical, scope, a nonlocal name is resolved by the source program’s nesting structure. P is declared at global level, alongside Q, rather than inside Q. The closest enclosing declarations for the a and b used in P are therefore the global variables.

Main first assigns those global variables (1,2). Q then creates a fresh activation containing its own local a,b. Although Q calls P, Q’s locals are not lexically enclosing declarations of P. P’s assignments update the globals to (5,10), leaving Q’s locals untouched. Q returns and its activation disappears. Main then prints the global values a=5,b=10.

A useful implementation view is that P’s static link identifies the global environment, independent of which procedure called it. The existence of same-spelled variables in the caller does not change this link. Their uninitialized values are irrelevant because P never reads or writes them under static scoping.

Original paper, page 6