Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the following pseudo-code when parameters are passed by reference and dynamic scoping is assumed?

a=3;
void n(x) {x = x * a; print(x);}
void m(y) {a = 1; a = y - a; n(a); print(a);}
void main() {m(a);}

  • A.6, 2
  • B.6, 6
  • C.4, 2
  • D.4, 4

Answer: D

The keyed output is 4, 4.

The pseudo-code has no declarations, so the key rests on reading the assignment a = 1 inside m as creating m's own local variable a (as an assignment does in many dynamically scoped languages). Under that reading:

  1. main calls m(a); y is a reference to the global a, which is 3.
  2. In m, a = 1 creates the local a; then a = y - a = 3 - 1 = 2.
  3. m calls n(a); x is a reference to m's local a. With dynamic scoping, the a inside n is the most recent active binding, m's local a, the same variable as x. So x = x * a = 2 * 2 = 4, and n prints 4.
  4. Back in m, print(a) prints the local a, now 4.

If every a were the single global variable, the output would be 0, 0 (a = 1, then a = y - a = 1 - 1 = 0), which is not offered; the options therefore assume the local reading. Under it, both prints show the same variable after n has changed it, which is why the two printed values are equal, ruling out 6, 2 and 4, 2.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.