Here's how recursion works: it adds stackframe over stackframe until it gets to the deepest level (i.e: there is a result). Consider the following function:
1 2 3 4 5 6
|
int recursion(unsigned i)
{
return i == 0 ? 1 : recursion(i-1) + 1;
}
//........... using the function
recursion(5);
|
So now, a stackframe is added:
And as it continues, the height of the stack will grow.
--STACK--
recursion(1)
recursion(2)
recursion(3)
recursion(4)
recursion(5)
|
It will finally stop when it hits a result
--STACK--
recursion(0) => returns 1 ("palpable" result)
recursion(1)
recursion(2)
recursion(3)
recursion(4)
recursion(5)
|
Now it will work from top to bottom, poping stackframes, calculating the result for every previous call now that it has something to start from.
--STACK--
recursion(0) => returns 1 ("palpable" result), pops stackframe
recursion(1) => recursion(0) + 1 = 1+1 = 2, pops stackframe
recursion(2) => and it continues
recursion(3)
recursion(4)
recursion(5)
|
Until it calculates the result of the original call (which is recursion(5)) and returns it.
Now some points about recursion:
* not very efficient in C-like languages (there are some exceptions though)
* pay attention if you pass arguments as references
* most of the time, a recursive algorithm may be implemented in a iterative way or using a stack data structure, both of which are less prone to overflow
* in C, you can use recursion to simulate a stack (since you actually use a stack when doing recursive calls), but there's no reason to use it as such in C++ since you already got std::stack