this is the expected result. the following function calls are pushed onto the stack, and the printf command will not be executed until the previous function call returns.
foo(3)
now x is not> = 1, so there are no more function calls and foo (0) is not popped from the stack. printf from foo (1) is executed and 0 (since the value of x has decreased) goes to stdout. another call to foo ():
foo(3) --> foo(2) --> foo(1) --> foo(-1) // ^^ second foo() call from foo(1)
current output:
0
it does nothing. foo (-1) and foo (1) are stacked.
now printf is called from foo (2) and 1 goes to stdout.
call foo (0).
foo(3) --> foo(2) --> foo(0) // ^^ second foo() call from foo(2)
current output:
01
foo (0) does nothing, then pop foo (0) and foo (2) the stack.
now we are in foo (3). type 2 and call foo (1).
foo(3) --> foo(1) // ^^ second foo() call from foo(3)
current output:
012
foo (1) calls foo (0), then prints 0, and then calls foo (-1). now all remaining foo are unloaded from the stack, and you get 0120 on exit.
@haccks - see this program. there are calls to foo (-1).
#include <stdio.h> void foo(int); int main() { foo(3); return 0; } void foo(int x) { if (x >= 1) { printf("executing foo with x = %d\n",x-1); foo(--x); printf("original output: %d\n", x); printf("executing foo with x = %d\n",x-1); foo(--x); } }
output:
executing foo with x = 2 executing foo with x = 1 executing foo with x = 0 original output: 0 executing foo with x = -1 original output: 1 executing foo with x = 0 original output: 2 executing foo with x = 1 executing foo with x = 0 original output: 0 executing foo with x = -1
source share