What is the return value of f (p, p) if the value of p is equally initialized to 5 before the call? Note that the first parameter is passed by reference, while 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:
I am trying to explain:
There will be four recursive calls in this code with parameters (6,4), (7,3), (8,2) and (9,1). The last call returns 1. But due to the passage by reference x in all previous functions is now 9. Therefore, the value returned by f (p, p) will be 9 * 9 * 9 * 9 * 1 = 6561.
This question is related to the GATE competitive exam, ( see Q.no.-42 ). The response key is set by GATE "Marks for all" (means that there is no correct option.) Key set-C, Q.no.-42 . Somewhere explained as:
In GATE 2013, the marks were marked by everyone, since the same code in C / C ++ creates undefined behavior. This is because * not a sequence point in C / C ++. The correct code should replace
return f(x,c) * x;
with
res = f(x,c); return res * x;
But this code is working fine. Is the GATE key wrong? Or is it really a mistake with a question?
user4791206
source share