What is the return value of , if the value of is initialized to 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;
}View worked solution
Answer: 6561
To find the return value of with initialized to , we analyze the parameter passing mechanisms:
- The first parameter
xis passed by reference, meaningxis an alias for the variablep. Any modification toxdirectly updatesp. - The second parameter
cis passed by value, meaningcis a local copy ofp's value at the time of the call.
Let's trace the execution step-by-step:
- Call 1: where
cbecomes .x = x + 1increments to .- Returns
f(x, 4) * x.
- Call 2: where
cbecomes .x = x + 1increments to .- Returns
f(x, 3) * x.
- Call 3: where
cbecomes .x = x + 1increments to .- Returns
f(x, 2) * x.
- Call 4: where
cbecomes .x = x + 1increments to .- Returns
f(x, 1) * x.
- Call 5: where
cbecomes .- Since
c == 0, it returns .
Now, we unwind the recursion. Since x is a reference to p, and the value of p is at the end of the recursion, any evaluation of x during the multiplication phase will use the current value of , which is :
- Call 4 returns:
- Call 3 returns:
- Call 2 returns:
- Call 1 returns:
Thus, the final return value is 6561.
Free practice · Your answers on this page are not saved.
