Reputation: 1843
I am trying to learn about recursion. I dont understand why the following piece of code runs in an infinite loop?
void myFunc(int n)
{
if(n==0)
return;
else
{
printf("%d\n",n);
myFunc(n--); //if I put n=n-1 before this line then it is running fine and will exit from the function .
printf("%d\n",n);
}
}
int main()
{
myFunc(4);
}
Upvotes: 1
Views: 152
Reputation: 942
n-- and --n are different. You should look up C operators and sequence points for the explanation. Basically, n-- means 'use n and decrement it at the next sequence point', whereas --n means 'decrement n first and then use it'..
Upvotes: 1
Reputation: 645
N-- is a postfix
operator. This means that it will increment the variable you are using it on after the value is used. As an example, in the expression x * y--
, the compiler will return x * y
, and then decrement y.
Upvotes: 0
Reputation: 10423
--
is a post-decrement operator as you are using it and only takes effect after myFunc
is called with the value of n
, so you will be calling myFunc
with the same value over and over again.
Using it as a pre-decrement operator would fix your particular use case: myFunc(--n)
would have a similar effect to putting n=n-1
on the line before.
Upvotes: 7
Reputation: 10841
n--
decrements n
after n
is passed to myFunc()
, so myFunc
is receiving the same n
value every time it is called.
Upvotes: 3
Reputation: 1002
n-- calls the postfix operation, which means the value of n gets passed into myFunc. After that, n's value is decremented by one. Call myFunc(--n).
Upvotes: 4
Reputation: 7457
Because the decrement is performed after the call. Not before.
If you do myFunc(--n);
instead, it will work
Upvotes: 3