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 above example, there are four possible answers to choose from:

  • 3024
  • 6561
  • 55440
  • 161051

The 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 variable x , which is transmitted by the standard, increases with each call to f (int & x, int c) and takes values 6-> 7 → 8-> 9 , the final result of this recursion is 9 ^ 4 . Therefore, my question is: the variable x is passed by reference and is equal to 9 when it reaches the base case. Does this mean that all stages of the recursion will have this value for the variable x, even if they had a different meaning when called?

+4
source share
1 answer

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

The extraction xfor calling the recursive function and the selection xfor the right side of the multiplication are not sequenced with each other; therefore, the evaluation procedure is unspecified.

This does not mean that the evaluation order will be any specific evaluation order, and this is only necessary for clarification. This means that the end results can:

  • Depends on the compiler.

  • Separate this program every time.

  • . . "Unspecified" "". . .

. , , -, , , .

, :

int y=x;

return f(x, c) * y;

:

int y=f(x, c);

return y * x;

.

+6

Source: https://habr.com/ru/post/1651158/


All Articles