Reputation: 59
I'm trying to understand the code below and i'm having a hard time understanding it.
It's very basic for you but for me it's quite a bit complicated. I would really appreciate your answer.
#include<stdio.h>
void fun(int);
int proc(pf, int, int);
int main()
{
int a=3;
fun(a);
return 0;
}
void fun(int n)
{
if(n > 0)
{
fun(--n);
printf("%d,", n);
fun(--n);
}
}
From what I understand fun takes 3 so--> fun(3)
and then it calls up the function until n
is not > than 0. so it must store 3,2,1,0 right?
But yet again it prints 0 because 0 is not bigger than 0.
What I don't understand is the printf
inside the if statement because we're printing if n>0
so when 0 is not bigger than 0 shouldn't it skip the statement? and return nothing?
I know what it's printing but i'm really trying to understand.
Let me know if my question was clear enough
Upvotes: 0
Views: 65
Reputation: 96018
I hope that this will illustrate it:
fun(3)
------
↓
fun(2) print → fun(1) ..
↓
fun(1) print → fun(0)
↓
fun(0) print → fun(-1)
Upvotes: 1
Reputation:
When n
is 1, control flow enters the if statement, but then n
is immediately decremented (fun(--n)
) so it becomes 0.
Upvotes: 2