What will be the output of the following pseudo-code when parameters are…

2016

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); }

Answer: D. 4, 4ConceptUnder call-by-reference, a formal parameter aliases the caller’s variable, so an assignment through the parameter updates the same storage. Under…

  1. A.

    6, 2

  2. B.

    6, 6

  3. C.

    4, 2

  4. D.

    4, 4

Attempted by 120 students.

Show answer & explanation

Correct answer: D

Concept

Under call-by-reference, a formal parameter aliases the caller’s variable, so an assignment through the parameter updates the same storage. Under dynamic scoping, a free name is resolved to the nearest active binding with that name in the call stack.

Application

  1. Initially, the global variable a has value 3. In m(a), the formal y is a reference to that global variable.

  2. The local a in m is set to 1. Then a = y - a gives a = 3 - 1 = 2, while y still refers to the global a.

  3. The call n(a) passes m’s local a by reference, so x in n aliases that local variable.

  4. Inside n, dynamic scoping resolves the free name a to m’s active local a. Therefore x = x * a evaluates as 2 * 2 and stores 4 in the same local variable.

  5. The print in n outputs 4. After n returns, m prints its local a, which is the same updated storage, so it also outputs 4.

Cross-check

Because x and m’s local a are aliases during n, both must contain the same value after x is assigned. Hence the two printed values cannot differ.

Result

The output is 4, 4.

Explore the full course: Iocl Engineers Officers Grade A Paper 2

Loading lesson…