Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This recursive function puzzles me, what is going on?

Tags:

c

recursion

I was playing around with recursion and did this simple function. I was assuming that it would print out 9-0 to stdout, but, it prints 0-9. I can't see how that happens at all.

int main()
{
        rec(10);
        return 0;
}

int rec(int n){
        if(n > 0)
                printf("%d\n", rec(n -1));
        return n;
}
like image 994
Fred Avatar asked Apr 06 '10 22:04

Fred


3 Answers

The rec function on the printf line is evaluated before the printf itself. Thus the deepest instance of the rec function is printed first.

like image 161
tloflin Avatar answered Nov 02 '22 12:11

tloflin


Think of it like this.

rec(10)
rec(9)
rec(8)
rec(7)
rec(6)
rec(5)
rec(4)
rec(3)
rec(2)
rec(1)
rec(0)

Start Unwinding

printf("%d\n", 0);
printf("%d\n", 1);
printf("%d\n", 2);
printf("%d\n", 3);
printf("%d\n", 4);
printf("%d\n", 5);
printf("%d\n", 6);
printf("%d\n", 7);
printf("%d\n", 8);
printf("%d\n", 9);
like image 40
ChaosPandion Avatar answered Nov 02 '22 14:11

ChaosPandion


Let's rewrite your code like this:

int rec(int n){
        if(n > 0)
        {
                int retval = rec(n -1);
                printf("%d\n", retval);
        }
        return n;
}

Does it make it clear why 0 printed first before 9?

like image 20
Lie Ryan Avatar answered Nov 02 '22 13:11

Lie Ryan