Hi folks,
As usual, reading about C, have hit a wall that I'm struggling to overcome, "recursion." As I understand it, it's like a function calling itself. This is the short program the author of the book I'm reading used to demonstrate it:
Code:
/* recur.c -- recursion illustration */
#include <stdio.h>
void up_and_down(int);
int main(void)
{
up_and_down(1);
return 0;
}
void up_and_down(int n)
{
printf("Level %d: n location %p\n", n, &n);
if(n < 4)
up_and_down(n+1);
printf("LEVEL %d: n location %p\n", n, &n);
}
The output:
Code:
Level 1: n location 0x7fff63d2761c
Level 2: n location 0x7fff63d275fc
Level 3: n location 0x7fff63d275dc
Level 4: n location 0x7fff63d275bc
LEVEL 4: n location 0x7fff63d275bc
LEVEL 3: n location 0x7fff63d275dc
LEVEL 2: n location 0x7fff63d275fc
LEVEL 1: n location 0x7fff63d2761c
I understand the program up to the point of the LEVEL 4 message being printed. The boolean test is false so the function moves on to that statement. Where I get lost is the program "backing out of" the recursion, so to speak.
This is what the author had to say starting with where I get confused:
When Level 4 is reached, n is 4, so the if test fails. The up_and_down() function is not called again. Instead, the Level 4 call proceeds to print statement #2, which prints LEVEL 4, because n is 4. Then it reaches the return statement. At this point, the level 4 call ends, and control passes back to the function that called it (the Level 3 call).
I at least understand why only the second print statement happens "on the way back out", because the function isn't being technically called again. But what does he mean by "reaching the return statement" though? That function is type void, so the only return I see in this program is "return 0" at the very end of int main(). If that's the case, why isn't the program ending before the all caps messages are printed? Why does the function have to "pass back control to the function that called it" ?
Any clarification would be greatly appreciated.