You're calling fun()
from within itself, both before and after the printf()
. So you're going to see the printf
from the deepest invocation of fun()
first.
@ForceBru is absolutely right, you can - and, if you want to be a programmer, need to be able to - trace the code out in your head or on paper. Here's an example.
on the first invocation of fun()
, as is 3. 3 > 0 so fun()
is called again, with the _pre_decremented value ( so n
is set to 2, and 2 is passed to fun()
.
The whole process happens again. 2 > 0 so --n
or 1 is passed to fun
.
In the 3rd invocation deep, n
is 1. That's still greater than 0, so fun(--n)
is run again, with n being predecremented to 0.
Now within the fourth invocation of fun()
, n is finally 0. Nothing happens.
Third invocation, first fun()
returns. Rember, this fun()
invocation's n
was 1, but it's been decremented to 0 by this time. 0 is printed. n
is then decremented again ( to -1, it being a signed int) and fun(-1)
is called, but since -1 > 0
is false, nothing happens. The third invocation returns.
The second invocation was passed 2 but has since decremented to 1. 1 is printed and then fun(--n)
turns into fun(0)
and the next fun() invcocation is
fun(-1)and also does nothing. The second invocation of
fun()` returns.
Finally, the first invocation of fun()
, the one from main, is executing agian. It started with 3, but decremented to 2. A 2 is printed. Then --n
, or 1, is passed to fun()
one last time. 1>0
so fun() is invoked again, and outputs
--1or 0 just like it did the first time it was passed a 1. The first invocation's recursive calls to
fun()then finish, and the program finishes, having output a
0, 1, 2, 0`.
Do walk through that yourself on paper, as recursive functions can be pretty confusing. I didn't understand why you got that output myself until I walked through the code, and I've been programing in c for 20 years!