Alex Rivera | Logout

This recursive function puzzles me, what is going on?

Asked 2010-04-06T22:04:40.943
12

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;
}
Edit
Report

2 Answers

19

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

answered 2010-04-06T22:06:57.550
3

Because you're creating 9 ambients 9 > 8 > 7 > 6 > 5 > 4> 3 > 2 > 1 > 0, now these ambients are treated the same this would a(b(c(d(e(f(g())))))), going from the deepest one to the first one.

Remember that when you do this printf("%d",n(m)); you're actually not printing anything, you're saying "print the result of n(m)" then when it tries to resolve n(m) you're calling another print and saying once again "resolve n(m-1)".

Now, when you reach n(0) it will return 0 to be printed by the last call of printf, therefore it prints 0 then 1 .. 9.

answered 2010-04-06T22:36:31.907

Your Answer