GATE | GATE-CS-2016 (Set 1) | Question 46

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)

Explanation:

a = 3;

void main() 
{  
   // Calls m with 'a' being passed by reference
   // Since there is no local 'a', global 'a' is passed. 
   m(a);
} 


// y refers to global 'a' as main calls "m(a)"
void m(y) 
{
   // A local 'a' is created with value 1.
   a = 1; 

   // a = 3 - 1 = 2
   a = y - a; 

   // Local 'a' with value 2 is passed by 
   // reference to n()
   n(a); 

   // Modified local 'a' is printed
   print(a);
}

// Local 'a' of m is passed here
void n(x) 
{
  // x = 2 * 2 [Note : again local 'a' is referred
  //                   because of dynamic scoping]  
  x = x * a; 

  // 4 is printed and local 'a' of m() is also
  // changed to 4.
  print(x);
}

Leave a Reply

Your email address will not be published. Required fields are marked *