I have a question about recursive functions

When a recursive function is called, I know the function will keep calling itself until a certain condition has been meet. But there's something that i don't understand about recursion. If you look at the code below, the function "function" will be called 5 times and will display a message 5 times. But right after the "if" statement, the same variable is being incremented. I dont understand how "num" is being incremented.

Please see the code below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

void function (int);

int main ()
{
    function (5);
}


void function (int num)
{
    cout << "You have " << num << " tries left" << endl;

    if (num > 0)
    {
        cout << "Make sure you try well" << endl;
        function (num - 1);
    }

    cout << "This is what i dont understand " << num;    //how is num being incremented?
    cout << endl;
}
Actually, num isn't being incremented. What's happening is you're printing out what num is (0 at the last recursive call) then returning to the previous function, where num is 1, which returns again to where num is 2... This repeats until you're all the way out.

Each recursively called function is waiting at line 20 for the function to return, after which it executes the remaining lines.
Hmm, so let me get this straight. When you call a function recursively, then you are basically in another "instance" of the function? (I don't know if i should use the word instance)

And the function will only end once it is "out" of the recursive calls? (i probably worded this out weirdly)
Something like that. As far as the function call goes, line 20 behaves just like line 9. Look at your function and run through it in your head starting from main:

function() is called, passed 5, main() waits for function() to return.
-output to console
-if (5 > 0)
--output to console
--function() is called, passed 5 - 1, function() waits for function() to return
---output to console
---if (4 > 0)
----output to console
----function() is called, passed 4 - 1, function() waits for function() to return
...
And so on

Topic archived. No new replies allowed.