我试图预测这个程序的输出:
#include
void fun(int x)
{
if (x > 0)
{
fun(--x);
printf("%d\t", x);
fun(--x);
}
}
int main()
{
int a = 4;
fun(a);
getchar();
return 0;
}
这个程序的输出是:
0 1 2 0 3 0 1
我知道很难用术语来解释,但我想知道的是,当 4 作为参数传递时,首先声明 fun(4--)
即 fun(3)
被执行,所以从这里调用 fun(3)
或打印 3
然后 fun(3--)
语句执行为基本上我对以下顺序感到困惑:
fun(--x);
printf("%d\t", x);
fun(--x);
这3条语句被执行。
发生的事情是:
call to fun(4)
-> call to fun(3)
-> call to fun(2)
-> call to fun(1)
-> call to fun(0) which prints nothing and returns
-> printing 0
-> call to fun(-1) which prints nothing and returns
<- execution returns to fun(2), where 1 is printed
-> in fun(3) 2 is printed and fun(1) called
-> fun(1) prints 0
<-
<-
-> in fun(4) 3 is printed and fun(2) called
-> fun(2) prints 0 1
通常,观察带有基本参数的调用行为是一种很好的做法,即在您的情况下:
-
fun(x)
其中 x <= 0
- 跳过条件,返回,不打印任何内容
-
fun(1)
- 电话 fun(0)
, 打印 0
, 来电 fun(-1)
- 即打印 0
-
fun(2)
- 电话 fun(1)
打印0
, 打印 1
, 来电 fun(0)
- 即打印 0 1
然后您可以在纸上画出执行流程,当您看到这 3 个中的一个时,您就已经知道结果了。就像我上面的例子一样,最后我看到 fun(2)
我看了之前发生的事情 fun(2)
被调用并看到“啊是的,fun(2)
打印 0 1
”。希望这有帮助;)
我是一名优秀的程序员,十分优秀!