Understanding Return better!?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int ff(int x){
    if(x==1){
        return 1;
    }else{
        return x*ff(x-1);
    }
}

int main()
{
cout << ff(5) << endl;
}


I guess i am getting a little caught up on how this program runs when it hits the return in function ff.

How I understand it is 5 is passed into function ff from main it this skips the if statement and goes to the else where the program would execute 5 and hit ff(x-1) and would cause it to run from the top with 4 and then 3 and so on. But at this point i'm not sure about this.

also when i play around with the program the final return value when changed always multiples the answer by that number so does return always when used with numbers cause it to multiple the answer

also where is the return value held does the program allocate space for the return value?

I am trying to explain my problem as well as i can but am so confused after thinking about it sorry if this makes no sense.

recursion can be tricky to understand

 
ff(x) = x*ff(x-1)

and
 
ff(1) = 1



So if you call ff(5)...

1
2
3
4
5
ff(1) = 1
ff(2) = 2 * ff(1)   : or... ff(2) = 2 * 1
ff(3) = 3 * ff(2)   : or... ff(3) = 3 * 2 * 1
ff(4) = 4 * ff(3)   : or... ff(4) = 4 * 3 * 2 * 1
ff(5) = 5 * ff(4)   : or... ff(5) = 5 * 4 * 3 * 2 * 1
also where is the return value held does the program allocate space for the return value?

Yes, each function call creates a new stack frame with the parameters, return value etc.
For more information, see: http://en.wikipedia.org/wiki/Call_stack
Topic archived. No new replies allowed.