GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 22(ii)

Dynamic scope follows the call chain

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

GATE 1994, Q22(ii) Descriptive
Report issue

Runtime Environments & Parameter Passing

Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Tap to enlarge
Answer & solution

Answer: 2, 5, 2 (without separators, 252). (no official key was published)

Under dynamic scoping, resolve an unbound local name by searching active callers, nearest first. Procedure two itself has no r. In the first call main→two, the closest active declaration is main's r, already set to 2, so two prints 2.

The second relevant call chain is main→one→two. Procedure one has an active local r initialized to 5. The search from two finds that declaration before reaching main, so this invocation prints 5. Procedure two merely reads the variable; it does not copy the value into main's r or assign to either declaration.

After one returns, its local r is no longer in the active call chain. The last main→two call therefore finds main's original r=2 and prints 2. The resulting sequence is 2,5,2, or 252 if ordinary write operations introduce no spaces. The key distinction is lifetime plus dynamic caller order: the same body of two can access different storage on different calls under dynamic scoping, whereas static scoping would always bind its r to main's lexical declaration. This result concerns the hypothetical dynamic-scoping interpretation requested, not the default rules of Pascal.

Original paper, page 6