GATE / CS ARCHIVE

GATE CSE 2003 / QUESTION 73

Static scope with call-by-need evaluation

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

GATE 2003, Q73 2 marks · MCQ
Report issue

Runtime Environments & Parameter Passing

Question 73, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses static scoping and call-by-need, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 73, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses static scoping and call-by-need, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 73, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses static scoping and call-by-need, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Under static scope the actual expression i+j is bound to the globals visible at the call in main. P's local i does not replace that lexical binding.
2. Call-by-need postpones evaluation until first use and caches its result. At print(x+10), the actual is first demanded: global i+j=100+5=105. The first print is 105+10=115.
3. P then sets its own local i to 200 and global j to 20. Neither assignment changes the cached value 105.
4. The second print reuses that value, giving 105. Therefore D. Recomputing 100+20 would be call-by-name, not call-by-need.

Solution: Under lexical scope the delayed actual expression i+j refers to main's enclosing global bindings, initially 100 and 5. Its first demand evaluates and memoizes 105, so print(x+10) emits 115. Assigning 200 to P's local i and 20 to global j cannot change the already cached actual value. The later print(x) emits 105. Thus D, 115 followed by 105. Call by need evaluates once on first demand; it is not repeated call-by-name evaluation.

Original paper, page 11