Karl
Karl

Reputation: 97

Why doesn't return statement end a recursive function in c?

Here is the code I am working with:

#include <stdio.h>

int f_b(int n, int a[n]);

int main() {
    int a[4] = { 7, 6, 5, 4 };
    printf("\n return: %d \n", f_b(4, a));
}

int f_b(int n, int a[n]) {
    int m;
    if (n == 1)
        return a[0];
    m = f_b(n - 1, a);
    printf("m:%d", m);
    if (m > a[n - 1]) {
        printf("\n m was greater than the last item\n ");
        return a[n - 1];
    } else
        return m;
}

And here is the output it gives:

m:7
m was greater than the last item
m:6
m was greater than the last item
m:5
m was greater than the last item

return: 4 

I was originally thinking that the code block in f_b coming after the first printf would be unreachable because the recursive part would keep counting down until until n is 1, with would return the first item of the array. I assumed the code would not go past the m = f_b(n-1, a); line until it has returned it's last value, then go on to the if-else statement. It appears that it will go through the if-else each recursive call?

I noticed the first item of the array was not being returned each time, which prompted me to litter the function with printf statements. I don't understand how the line "m was greater than the last item" can be reached so many times when there is also a return a[n-1] statement that I would assume jumps out of the the function. I get that it is jumping out of each recursive call but then why wouldn't it always return a[0] when it finishes its recursive calls?

Please correct my thinking here as the output (as I see) demonstrates a return statement being reached, but also being passed over. Is it being reached so many times because of the recursion? If so, what is stopping the code in the end (because n can be counted down indefinitely)

Upvotes: 0

Views: 2148

Answers (1)

Karl
Karl

Reputation: 97

Each recursive call the function has a return value, returning on a call later on does not jump out of the recursion to main, it just jumps out to the previous call. This is how it can reach multiple return statements.

As each call resolves on the stack, the function will complete through the rest of the code, this is how we reach code that comes after the recursive call (in f_b)

If I'm not mistaken, this function returns the smallest value in the array.

Upvotes: 2

Related Questions