Search code examples
c++pass-by-referencepass-by-value

Tricky Pass by Value and Pass by Reference Recursion Question


The following is the code snippet from C++. The right answer is 6561, but i don't quite understand why. I totally understand how the recursion runs behind the scene, but i cannot tell why the result is totally different between pass &x (reference) and x (value) into the function. Would anyone help me out? I am sooooo confused...much appreciated!

My step-by-step understanding is that every recursion do the calculation of c = c - 1 and x = x + 1 and pass the value into the recursive fun(x, c) as opposed to the right answer, which is to keep the same copy for x, shown as the following:

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;

}

Solution

  • 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
    

    Hope this helps