Dimos Nt
Dimos Nt

Reputation: 67

Use pass by reference in recursion

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:

  1. 3024
  2. 6561
  3. 55440
  4. 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?

Upvotes: 6

Views: 2854

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118445

No, there are more than four answers to choose from.

The fetch of x for the recursive function call, and the fetch of x for the right hand side of multiplication, is not sequenced with each other; and as such the evaluation order is unspecified.

This doesn't mean that the evaluation order would be some particular evaluation order, and it's only necessary to figure it out. This means that the final results can:

  1. Vary depending on the compiler.

  2. Vary each time this program executes.

  3. The evaluation order may also be different for each individual recursive call. Each recursive call can end up using a different evaluation order, too. "Unspecified" means "unspecified". Any possibility can happen. Each individual time.

I didn't bother to calculate all actual possibilities here. It's better to invest one's own time on something that should work properly, instead of on something that obviously can never work properly.

If you want a specific evaluation order, it's going to be either this:

int y=x;

return f(x, c) * y;

Or this:

int y=f(x, c);

return y * x;

This evaluation order is now specified.

Upvotes: 9

Related Questions