recategorized by
21,003 views
73 votes
73 votes

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;
}
recategorized by

2 Answers

Best answer
109 votes
109 votes

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); // ';' forms a sequence point 
//and all side-effects are guaranteed to be completed here 
//-- updation of the x parameter inside f is guaranteed 
//to be reflected in the caller from the next point onwards. 
return res * x;

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$.

Good Read:

edited by
2 votes
2 votes
I think Answer is (B)
Since c is passed by value and x is passed by reference, all functions will have same copy of x, but different copies of c.
f(5, 5) = f(x, 4)*x = f(x, 3)*x*x = f(x, 2)*x*x*x = f(x, 1)*x*x*x*x = 1*x*x*x*x = x^4
Since x is incremented in every function call, it becomes9 after f(x, 2) call. So the value of expression x^4 becomes 9^4 which is 6561
Answer:

Related questions

45 votes
45 votes
3 answers
1
gatecse asked Aug 21, 2014
11,812 views
Which one of the following is NOT logically equivalent to $¬∃x(∀ y (α)∧∀z(β ))$ ?$∀ x(∃ z(¬β )→∀ y(α))$$∀x(∀ z(β )→∃ y(¬α))$$∀x(∀ y(�...
22 votes
22 votes
3 answers
4