When you call a function, the function body executes. When that function returns, the return value is fed to the code that called it. IE:
1 2 3 4 5 6 7 8 9 10 11
|
int foo()
{
int butt = 3;
butt += 2;
return butt;
}
int main()
{
cout << foo();
}
|
Here, when main calls 'foo', foo's body will execute... all it's code will run... and it will return a value (in this example it returns 5).
That value is fed back to the code that called it (here, it gets fed back to main, since main called foo). The function call evaluates to whatever the function returned... so since we are sending the foo() call to cout... we're
actually sending the value foo returns to cout. Since foo() returns 5, this will send 5 to cout... which will print 5 to the user.
Recursive calls are no different. A called function gets executed and the returned value gets fed back to whoever calls it. The only change is that the function is calling itself.
So when we call
mystery(5,3)
from main... the flow works like this:
1) main calls mystery(5,3)
2) mystery(5,3) calls mystery(5,2)
3) mystery(5,2) calls mystery(5,1)
4) mystery(5,1) doesn't call anything, but instead just returns 5
5) execution returns to mystery(5,2), which takes the returned value (5), adds 5 to it, and returns it (returning 10)
6) execution returns to mystery(5,3), which takes the returned value (10), adds 5 to it and returns (returning 15)
7) execution returns to main, with the value of 15 having been returned.
mystery does not "remember" previous calls. Each time you call it, its logic is rerun and its value is recalculated.