这是预期的输出。下一个函数调用被压入堆栈,直到上一个函数调用返回时才会执行 printf 语句。
foo(3) --> foo(2) --> foo(1) --> foo(0)
现在 x 不 >=1,因此不再有函数调用,并且 foo(0) 被弹出堆栈。来自 foo(1) 的 printf 语句被执行并且 0(因为 x 值被递减)进入标准输出。另一个 foo() 调用:
foo(3) --> foo(2) --> foo(1) --> foo(-1)
// ^^ second foo() call from foo(1)
当前输出:
0
这没有任何作用。 foo(-1) 和 foo(1) 从堆栈中弹出。
现在 printf 从 foo(2) 调用,1 进入标准输出。
调用 foo(0)。
foo(3) --> foo(2) --> foo(0)
// ^^ second foo() call from foo(2)
当前输出:
01
foo(0) 什么都不做,然后弹出堆栈的 foo(0) 和 foo(2)。
现在我们在 foo(3) 中。打印 2 并调用 foo(1)。
foo(3) --> foo(1)
// ^^ second foo() call from foo(3)
当前输出:
012
foo(1) 调用 foo(0) 然后打印 0 然后调用 foo(-1)。现在所有剩余的 foo 都从堆栈中弹出,输出为 0120。
@hacks - 看到这个程序。有对 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);
}
}
输出:
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