in Programming in C recategorized by
21,118 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;
}
in Programming in C recategorized by
by
21.1k views

4 Comments

Just a simple doubt.

Is marks for all means, Is it only to those who attended this question

OR

To everyone , who didn’t even attend this question also ?
1
1
Is it at all a valid C code? I doubt…

They some how tried to test the concept in some pseudo language which supports both pass by reference and pass by value…
0
0
how can you increase the address. shouldn’t the program send segmentation fault.
0
0

2 Answers

109 votes
109 votes
Best answer

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
by

4 Comments

awesome answer
0
0
$&x$ will evaluate to address of the pointer and not the value of p. As mentioned in the question, the value of p(first parameter) is passed by reference so it must be something like this:

$f(&p, p)$

$f(&x, c)$

where $x = &p$ and $*x = value of p = 5$ and  $&x = address of the pointer$. So why are we substituting &x as *x?
1
1

If you are having doubt regarding the use of $\&$ in the code read this : https://stackoverflow.com/questions/6877052/use-of-the-operator-in-c-function-signatures

string s = "Hello, wordl";
string* p = &s; // Here you get an address of s
string& r = s; // Here, r is a reference to s    
0
0
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