我试图预测这个程序的输出:
#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;
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出是:
0 1 2 0 3 0 1
Run Code Online (Sandbox Code Playgroud)
我知道很难用术语来解释,但我想知道的是当4作为参数传递而不是第一个语句fun(4--)
即fun(3)
执行时,所以从这里做一个调用fun(3)
或者3
打印然后fun(3--)
语句被执行,因为基本上我是对以下顺序感到困惑:
fun(--x);
printf("%d\t", x);
fun(--x);
Run Code Online (Sandbox Code Playgroud)
执行这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
Run Code Online (Sandbox Code Playgroud)
通常,使用基本参数观察调用的行为是一种很好的做法,即在您的情况下:
fun(x)
where x <= 0
- 跳过条件,返回,没有打印fun(1)
- 通话fun(0)
,打印0
,通话fun(-1)
- 即打印0
fun(2)
- fun(1)
打印0
,打印1
,打电话的fun(0)
打印 - 即打印0 1
然后你可以在纸上绘制执行流程,当你看到其中一个时,你已经知道了结果.就像我上面的例子一样,最后当我看到fun(2)
我看到发生之前发生的事情时fun(2)
,看到了"啊是的,fun(2)
打印0 1
".希望这可以帮助 ;)