GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 22(i)

Lexical scope in sibling procedures

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

GATE 1994, Q22(i) Descriptive
Report issue

Runtime Environments & Parameter Passing

Question 22(i), 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 static scoping?
Question 22(i), 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 static scoping?
Question 22(i), 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 static scoping?
Question 22(i), 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 static scoping?
Tap to enlarge
Answer & solution

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

Static, or lexical, scoping resolves a name by the nesting of declarations in the program text, not by whichever procedure happened to call the current procedure. Procedure two has no local declaration of r. Its immediately enclosing lexical scope is main, so every reference to r in two denotes main's r. Procedure one's local r is in a sibling procedure's scope and is not visible inside two.

After main assigns r=2, its first call to two prints 2. Next main calls one, which creates a separate local r and sets that local variable to 5. The call from one to two still resolves two's r to main's unchanged variable and therefore prints 2. Returning from one removes its local activation without changing main's r. The final direct call to two again prints 2.

Thus the sequence of values is 2,2,2. The pseudocode uses write rather than writeln and requests no separators, so a literal output stream would commonly appear as 222. Formatting conventions do not change the three values.

Original paper, page 6