Why is the output "false2", when the condition at the if block is 1 which is true ?
#include<stdio.h>
int main(){
int x=0;
if (x++)
printf("true1");
else if (x==1)
printf("false2");
return 0;}
Why is the output "false2", when the condition at the if block is 1 which is true ?
#include<stdio.h>
int main(){
int x=0;
if (x++)
printf("true1");
else if (x==1)
printf("false2");
return 0;}
when the condition at the if block is 1 which is true ?
That's not the case. The if
condition is actually false.
The expression x++
yields the current value of x
(which is what's used to test the condition) and then increments it. Since x
's current value is 0
, it evaluates to false and thus it goes into the else if
condition.
Contrast this with ++x
which increments first and then yields the new value.
x++
means first use the value of x
and then increment it's value by 1. So your if condition is if(0)
, Then x
value increments and becomes 1. So your else if condition is else if(1)
. Whereas ++x
means first increase the value of x
by 1 and then use it so your first condition is if(1)
.
The first time x
is tested, it is zero and then it is incremented:
//x is post-incremented, i.e. evaluated before being incremented
int x=0;
if (x++)//x is tested when x==0, then is incremented
printf("true1");
else if (x==1)//execution flow goes here...
printf("false2");//...then here
To make x
test as TRUE on the first iteration change it to a pre-increment:
//x is pre-incremented, i.e. incremented before being evaluated
int x=0;
if (++x)//x is incremented, then tested when x==1
printf("true1");//execution flow goes here...
else if (x==1)
printf("false2");
//...then here