Reputation: 31
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--)
i.e. 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:
fun(--x);
printf("%d\t", x);
fun(--x);
these 3 statements are executed.
Upvotes: 0
Views: 1828
Reputation: 42083
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, i.e. in your case:
fun(x)
where x <= 0
- skips condition, returns, nothing is printed fun(1)
- calls fun(0)
, prints 0
, calls fun(-1)
- i.e. prints 0
fun(2)
- calls fun(1)
which prints 0
, prints 1
, calls fun(0)
- i.e. prints 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
". Hope this helps ;)
Upvotes: 5
Reputation: 1909
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.
Upvotes: 0
Reputation: 9062
When you call fun(4):
I hope this clarifies things a bit for you.
Upvotes: 2