Gilles Van Hooff Gilles Van Hooff - 3 months ago 19
C Question

Recursion: don't understand this result

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.

Answer

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
Comments