Code: Select all
#include <iostream>
void recurse(int i);
int main(void)
{
recurse(0);
std::cin.get(); //Just to keep the display until a key is pressed
return 0;
}
void recurse(int i)
{
if (i < 10)
{
recurse (i + 1);
std::cout << i << std::endl;
}
}
If you put a breakpoint on recurse(i + 1) and f11 you will see all the recursions build up in the stack as expected but I don't get how they are being consumed.
I see "i" being incremented up to 10 but when it gets to 10 surely it should leave the "if" statement and it does, briefly, but not to go back to main() instead it goes back to the line recurse(i + 1) but instead of increasing "i" from 10 to 11 as one might expect, "i" reduces by 1 to 9 and outputs to the console, then back to recurse (i+1) and instead of incrementing "i", subtracts 1 and outputs the result. Round and round it goes consuming the stacked recursions.
This makes no sense to me at all.
Can anybody shed some clarity on this for a poor, confused old man?
Thanks in advance for any insight.
Alex Whitcombe (alias Frogmella Slob in YouTube comments)