mercredi 30 septembre 2015

Is undefined behavior in given code?

What is the return value of f(p,p), if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value.

int f (int &x, int c) {
       c = c - 1;
       if (c==0) return 1;
       x = x + 1;
       return f(x,c) * x;
}

Options are :

  1. 3024
  2. 6561
  3. 55440
  4. 161051

I try to explain :


In this code, there will be 4 recursive calls with parameters (6,4), (7,3), (8,2) and (9,1). The last call returns 1. But due to pass by reference, x in all the previous functions is now 9. Hence, the value returned by f(p,p) will be 9 * 9 * 9 * 9 * 1 = 6561.


This question is from competive exam GATE , (see Q.no.-42) . Answer key is given by GATE "Marks to all" (means there is no option correct.) key set-C, Q.no.-42. somewhere explained as :

In GATE 2013 marks were given to all as the same code in C/C++ produces undefined behavior. This is because * is not a sequence point in C/C++. The correct code must replace

return f(x,c) * x;
with
 res = f(x,c);
 return res * x;


But given code works fine , Is GATE's Key wrong? or Is really the mistake with question ?

Aucun commentaire:

Enregistrer un commentaire