我试图预测这个程序的输出:
#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个陈述。
答案 0 :(得分:5)
会发生什么:
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
然后你可以在纸上画出执行的流程,当你看到这三个中的一个时,你已经知道了结果。就像我上面的例子一样,最后当我看到fun(2)
时,我看到了fun(2)
被叫之前发生的事情并看到了“啊是的,fun(2)
打印0 1
”。希望这会有所帮助;)
答案 1 :(得分:2)
当你打电话给乐趣(4)时:
我希望这能为你澄清一些事情。
答案 2 :(得分:0)
流程:
main():
fun(4):
x is 3 and the following are called-
fun(3):
x is 2 and-
fun(2):
x is 1 and-
fun(1):
x is 0
the call to fun(0) returns, after having bottomed out, PRINT 0.
calls fun(-1)
call returns
when fun(1) returns, PRINT 1
x is 0
PRINT 2
fun(1)
x is 0
call to fun(0) returns
PRINT 0
call to fun(-1) returns
PRINT 3
fun(3)
x is 2
fun(2)
x is 1
fun(0) returns
PRINT 0
PRINT 1
我可能出错了,但这就是流程。