[英]can anyone please help me with the sequence of execution of this program
I was trying to predict the output of this program: 我试图预测该程序的输出:
#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;
}
the output of this program is: 该程序的输出为:
0 1 2 0 3 0 1
I know its tough to explain in terms but all I want to know is that when 4 is passed as an argument than firstly statement fun(4--)
ie fun(3)
is executed,so from here does a call to fun(3)
is made or 3
is printed then fun(3--)
statement is executed as basically I am confused about the sequence in which: 我知道很难用术语来解释,但是我想知道的是,当将4作为参数传递时,首先要执行
fun(4--)
即fun(3)
,所以从这里开始调用fun(3)
或打印3
,然后执行fun(3--)
语句,因为基本上我对以下顺序感到困惑:
fun(--x);
printf("%d\t", x);
fun(--x);
these 3 statements are executed. 这3条语句被执行。
What happens is: 发生的是:
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
Usually it is a good practice to observe the behavior of calls with elementary arguments, ie in your case:
fun(x)
where x <= 0
- skips condition, returns, nothing is printed fun(x)
其中x <= 0
跳过条件,返回,不打印任何内容 fun(1)
- calls fun(0)
, prints 0
, calls fun(-1)
- ie prints 0
fun(1)
-调用fun(0)
,打印0
,调用fun(-1)
-即打印0
fun(2)
- calls fun(1)
which prints 0
, prints 1
, calls fun(0)
- ie prints 0 1
fun(2)
-调用fun(1)
打印0
,打印1
,调用fun(0)
-即打印0 1
Then you can draw on paper the flow of execution and when you see one of these 3, you already know the result. 然后,您可以在纸上画出执行的流程,当您看到这三个中的一个时,您已经知道结果了。 Like in my example above, at the end when I saw
fun(2)
I looked what happened before when fun(2)
was called and saw "ah yeah, fun(2)
prints 0 1
". 就像上面的示例一样,最后当我看到
fun(2)
我看了调用fun(2)
之前发生的事情,并看到“是的, fun(2)
打印0 1
”。 Hope this helps ;) 希望这可以帮助 ;)
When you call fun(4): 当您调用fun(4)时:
I hope this clarifies things a bit for you. 我希望这对您有所帮助。
Flow: 流:
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
i might have gone wrong, but such is the flow. 我可能出了错,但这就是流程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.