Question
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;
}
Official answer and solution
- Official answer
- Marks to all
- From
- Official GATE 2013 answer key
Official GATE answer key awarded Marks to All for this question.
Solution
Trace the recursive execution of f(p, p) and examine the order of evaluation of multiplication operands with pass-by-reference.
The function definition is:
int f (int &x, int c) {
c = c - 1;
if (c == 0) return 1;
x = x + 1;
return f(x, c) * x;
}
We start with variable p = 5 and call f(p, p).
- Parameter
xis passed by reference top. Any modification toxdirectly updatesp. - Parameter
cis passed by value (starts with a copy of value 5).
Let us trace the successive recursive calls:
- Call 1:
p = 5.xrefers top,c = 5.cbecomes .xbecomes (sopis now 6).- Evaluates
return f(x, 4) * x;.
- Call 2:
xrefers top(currently 6),c = 4.cbecomes .xbecomes (sopis now 7).- Evaluates
return f(x, 3) * x;.
- Call 3:
xrefers top(currently 7),c = 3.cbecomes .xbecomes (sopis now 8).- Evaluates
return f(x, 2) * x;.
- Call 4:
xrefers top(currently 8),c = 2.cbecomes .xbecomes (sopis now 9).- Evaluates
return f(x, 1) * x;.
- Call 5:
xrefers top(currently 9),c = 1.cbecomes .- Condition
c == 0is met, so it returns 1.
Now consider the expression return f(x, c) * x;:
In C and C++, the order of evaluation of the operands of the binary * operator is unspecified:
-
Case 1 (evaluate x after f(x, c) returns):
When Call 5 returns 1 to Call 4,x(which refers top) has value 9. Call 4 returns .
At Call 3,xis 9. It returns .
At Call 2,xis 9. It returns .
At Call 1,xis 9. It returns (Option B). -
Case 2 (evaluate x before calling f(x, c)):
Call 4 evaluates .
Call 3 evaluates .
Call 2 evaluates .
Call 1 evaluates (Option A).
Because the evaluation order of operands in multiplication is unspecified in the language standard, both 3024 and 6561 are defensible results depending on compiler implementation. Consequently, GATE officially awarded Marks to All.
Marks to All
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2013 Computer Science and Information Technology (CS)
- Question
- 42 of 65, printed as CS Q.42
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.