4
void func(int num){
    if(num< 3){
        printf("%d ", num);
        func(num+ 1);
        printf("%d ", num);
    }
}

Suppose I call this function with func(0). Why is the result 0 1 2 2 1 0 ? I don't know why it's decreasing.

  • 5
    The first three numbers come from the first printf, and the second three numbers come from the second printf as the stack unwinds. To see that better, try `"a:%d "` and `"b:%d "` as the format strings. – user3386109 Aug 16 '16 at 21:30
  • Yeah I get that, but why is it going from 2 to 0, it doesn't make sense to me? – Gilles Van Hooff Aug 16 '16 at 21:32
  • Your code does nothing since the function is never called. – John Coleman Aug 16 '16 at 21:32
  • Yeah I call it in the main, didn't think it was necessary to post that.... – Gilles Van Hooff Aug 16 '16 at 21:33
  • 1
    Try to ask yourself, **when** does the second `printf` get called on any iteration? – vgru Aug 16 '16 at 21:37
  • In your original question you didn't even state what value you called it with. Readers shouldn't need to infer that (not that it is very hard). – John Coleman Aug 16 '16 at 21:37
  • 1
    Possible duplicate of [Problems with understanding how recursion works in C](http://stackoverflow.com/questions/27768992/problems-with-understanding-how-recursion-works-in-c), or [Understanding recursion in the beer bottle example](http://stackoverflow.com/q/20714617/69809), or [Understanding how recursive functions work](http://stackoverflow.com/q/25676961/69809). – vgru Aug 16 '16 at 21:39
  • Sorry John. Thanks for the help guys, I understand now! – Gilles Van Hooff Aug 16 '16 at 21:49

1 Answers1

11

Here's a stack trace

f(0)
    print 0
    f(1)
        print 1
        f(2)
            print 2
            f(3)  // 3 < 3 == false
            print 2
         print 1
     print 0
CMPS
  • 7,733
  • 4
  • 28
  • 53