GATE / CS ARCHIVE

GATE CSE 1991 / QUESTION 9(a.iii)

Call by name re-evaluates the expression

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

GATE 1991, Q9(a.iii) Descriptive
Report issue

Runtime Environments & Parameter Passing

Question 9(a.iii), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by name.
Question 9(a.iii), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by name.
Tap to enlarge
Answer & solution

Answer: x=2,z=12. (no official key was published)

Call by name delays evaluation of an actual argument until its formal is used, in the caller’s environment. Think of a as a getter/setter for x, b as a thunk returning x*y, and c as a getter/setter for z. The caller’s x and y, not unrelated locals inside P, are the names captured by b’s thunk.

The first statement a:=2 follows the location associated with x and changes x from 1 to 2. The next statement c:=a+b first obtains a=2 and evaluates b’s expression using the current caller state: x*y=2·5=10. It therefore writes 12 through c into z. After return, main prints x=2,z=12.

A textual substitution illustrates this particular collision-free example: x:=2; z:=x+x*y. General call-by-name implementations must preserve environments and avoid accidental name capture, so literal substitution is only an explanatory model. The difference from temporary-backed reference passing is that b is not frozen at its original value 5. The nonassignability of x*y does not prevent this example’s by-name use because b is only read, never assigned.

Original paper, page 6