棘手的按值传递和按引用传递递归问题

Tricky Pass by Value and Pass by Reference Recursion Question

以下是 C++ 的代码片段。正确答案是 6561,但我不太明白为什么。我完全理解递归是如何在幕后运行的,但我不知道为什么将 &x (引用)和 x (值)传递给函数的结果完全不同。有人会帮我吗?我很困惑...非常感谢!

我一步一步的理解是每次递归都会计算 c = c - 1 和 x = x + 1 并将值传递给递归 fun(x, c) 而不是正确答案,也就是为x保留同一份,如下图:

f(5,5) = f(6,4) * 6

f(5,5) = f(6,4) * 6 = f(7,3) * 6 * 7

f(5,5) = f(6,4) * 6 = f(7,3) * 6 * 7 = f(8,2) * 6 * 7 * 8

f(5,5) = f(6,4) * 6 = f(7,3) * 6 * 7 = f(8,2) * 6 * 7 * 8 = f(9,1 ) * 6 * 7 * 8 * 9 = 1 * 6 * 7 * 8 * 9 = 3024

#include <iostream>
int f(int &x, int c) {
   c  = c - 1;
   if (c == 0) return 1;
   x = x + 1;
   return f(x, c) * x;
} 

int main(){

  int a = 5; 
  int b = 5; 

  std::cout<<"final result is " << f(a,b) << "\n";

return 0;

}
f(5,5) -> c = 4; a = x = 6
f(6,4) -> c = 3; a = x = 7
f(7,3) -> c = 2; a = x = 8
f(8,2) -> c = 1; a = x = 9
f(9,1) -> c = 0; return 1;

-----

f(8,2) returns 1 * x = 9
f(7,3) returns 9 * x = 9 * 9 = 81
f(6,4) returns 81 * x = 81 * 9 = 729
f(5,5) returns 729 * x = 729 * 9 = 6561

希望对您有所帮助

return f(x, c) * x;

因为它指的是 x 的值与 f(x,c) 中的 x 的值不同,并且与乘法值 *x 不同。后者在 f(x,c) 调用结束后发生了变化。