我试图预测这个程序的输出:
#include
void fun(int x)
{
if (x > 0)
{
fun(--x);
printf("%dt", 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("%dt", 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
- 跳过条件,返回,不打印任何内容 0
,调用fun(-1)
- 即打印0
1
,调用fun(0)
- 即打印0 1
fun(1)
- 调用fun(0)
,打印fun(2)
- 调用fun(1)
,打印0
,打印然后你可以在纸上画出执行流程,当你看到这 3 个中的一个时,你已经知道结果了。就像我上面的例子一样,最后当我看到fun(2)
时,我看了之前发生的事情,当fun(2)
被召唤并看到"啊,是的,fun(2)
打印0 1
"。希望这对;)有所帮助
当你调用fun(4(时:
- 它叫乐趣(3(
- 趣味(3( 叫乐(2(
- 乐趣(2( 调用乐趣(1(
- 趣味(1( 呼唤乐(0(
- 乐趣(0( 结束无所事事
- 它返回 fun(1(,其中 x 从 --x 变为 0 并显示它,并调用 fun(-1(,它什么也不做。现在 fun(1( 完成了它的工作
- 它以 fun(2( 返回,显示 1 并调用 fun(0(,它什么也不做。现在fun(2(完成了它的工作。
- 它以 fun(3( 返回,显示 2 并调用 fun(1(。如上所述,fun(1( 显示 0。
- 它以 fun(4( 的形式返回,显示 3 并调用 fun(2(。如上所述,fun(2( 显示 0 1。
我希望这能为您澄清一些事情。
流:
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
我可能出错了,但这就是流程。