what I don't quite understand, from @dhayden's example, is how we "get back" inside the if-statement after |
Consider this code:
1 2 3 4 5 6 7 8 9 10 11
|
void otherFunc(char *cp)
{
cout << "I am another function called with " << cp << '\n';
}
void func(char* Cstr) {
if (*Cstr != '\0') {
otherFunc(Cstr + 1); // call another function
cout << *Cstr; // then print the string
}
}
|
Here func() is the same as yours with just one exception: it calls otherFunc() instead of func().
Do you see how the program calls otherFunc()? See how otherFunc() runs and when it returns, the program continues inside the
if
statement?
Of course you do :). This is easy. It's just a normal function call.
The key is that when you call a function recursively, it's no different! Returning to my program, after printing "Leaving func("")", that call to func() returns. Where was it called from? It was called from inside the if statement, so that's where it returns to! Each call returns to the point where it was called.
It might also help to realize that, even though the program executes the same code several times,
each call creates its own separate Cstr parameter and return address. The returns address is like a hidden parameter to the function that tells the program where to resume execution when it returns. That's how it knows to return to the
if
statement for the recursive calls, and the main program for the first call.
Does this make sense?