GATE / CS ARCHIVE

GATE CSE 2003 / QUESTION 74

Dynamic scope with call-by-name evaluation

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

GATE 2003, Q74 2 marks · MCQ
Report issue

Runtime Environments & Parameter Passing

Question 74, 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 dynamic scoping and call-by-name, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 74, 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 dynamic scoping and call-by-name, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 74, 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 dynamic scoping and call-by-name, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Call-by-name reevaluates the actual expression i+j whenever x is used. Under the stipulated dynamic scope, name lookup uses the nearest active bindings.
2. During the first print, P's local i=10 is nearest, while j resolves to global 5. Thus x=15 and x+10=25.
3. The assignments make the active local i=200 and global j=20. The second use reevaluates i+j as 220, rather than retaining 15.
4. The output is 25,220, B. This is specifically the question's dynamic-name interpretation, not lexical capture of main's i.

Solution: In the question's dynamic-scoping, call-by-name model, the actual expression i+j is reevaluated at each use with the active dynamic bindings. At the first print, i is P's local 10 and j is the global 5, so x+10 is 25. P then changes its local i to 200 and global j to 20. The second evaluation of x gives 220. Hence B. This uses the stipulated dynamic-name lookup rather than lexical capture of the actual expression.

Original paper, page 11