在这种情况下,调用 fun() 就像调用任何其他函数一样。例如:
int main() {
int a = 0;
foo(a);
printf("main a = %d\n", a);
}
void foo(int a) {
a = 1;
bar(a);
printf("foo a = %d\n", a);
}
void bar(int a) {
a = 2;
printf("bar a = %d\n", a);
}
您的调用顺序如下所示:
main();
foo();
bar();
你的输出将是这样的:
bar a = 2
foo a = 1
main a = 0
参数是按值传递的,因此a
是复制的,实际上是每个函数中的不同变量。递归也是如此。
main(); x = 3
fun(3); a = 3, so a > 0, nothing happens, return to main()
如果您要更改条件,那么 fun() 在 a > 0 时调用自身(自上而下阅读)
main(); x = 3
fun(3); a = 3, a > 0 so --a = 2, fun(2)
fun(2); a = 2, a > 0 so --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0) /* same as fun(1) above */
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2) /* same as fun(1) above */
fun(2); printf("%d", a) displays 2, --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0) /* this is a new fun(1) */
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2)
fun(2); nothing left to do so return to fun(3)
fun(3); printf("%d", a) displays 3, --a = 2, fun(2) /* halfway point */
fun(2); a = 2, a > 0 so --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2)
fun(2); printf("%d", a) displays 2, --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2)
fun(2); nothing left to do so return to fun(3)
fun(3); nothing left to do so return to main()
你的输出应该是: 1213121 它反映了调用的树结构:
3
/ \
/ \
2 2
/ \ / \
1 1 1 1