The first one is :
if(n--)
{
//do something
}
The second is :
if(n)
{
//do something
n--;
}
I'm not able to understand the difference between these two pieces of code. Both are giving different outputs.
CodePudding user response:
The first one always subtracts 1 from n
no matter what, when the condition of the if statement gets evaluated.
The second one will only subtract 1 from n
if n
was non-zero at the beginning of the code block, because the n--
is inside the first block of the if statement, and that block only runs if the condition is non-zero.
Both pieces of code are similar in that they will only execute the "do something" if n
was non-zero at beginning.
CodePudding user response:
The first one, n is the value substracted during "do something", the second one, n is the previous value during "do something".
CodePudding user response:
let say, n=1. For the first if, it is true and it will decrement 1 to 0 immediately. so if you print at the beginning of if you will see n=0. For the 2nd if, you will see n=1, then n-- will decrement it.
Run the below code, you will get it.
The first one is :
if(n--)
{
printf("%d\n",n);
//do something
}
The second is :
if(n)
{
printf("%d\n",n);
//do something
n--;
}