int f(int &x, int c)
{
c = c - 1;
if (c == 0) return 1;
x = x + 1;
return f(x, c) * x;
}
int x = 5;
cout << f(x,5);
In the example above the four possible answers to choose from are:
- 3024
- 6561
- 55440
- 161051
Function f(int &x, int c) is called four times after the first call before it reaches the base case where it returns the result which is 6561. My guess was 3024 but I was wrong. Even if the x variable which is passed by reference increments in each call of f(int &x, int c) and takes the values 6->7->8->9 respectively the final result of this recursion is equal to 9^4.
So my question is: Variable x is passed by reference and is equal to 9 when it reaches the base case. Does that mean that all the stages of recursion will have this value for variable x even if they had a different value when they've been called?
f(x, c) * x;modifies and also usesx. Unwinding a single round of recursion it simplifies to++x * xwhich is definitely UB.++x * x). "Unspecified" means that one of a finite number of things could happen (two in this case), but the standard doesn't specify which. Of course, in practice, "undefined" and "unspecified" are equivalently bad.