In my if
statement, the first condition for &&
is 0
(false), so the expression 0 && (a++)
is equal to 0
, right? Then 0==0
it should be true. Why am I getting else
here? Please explain!
int a=0;
if(0 && (a++)==0)
{
printf("Inside if");
}
else
{
printf("Else");
}
printf("%i",a);
The ==
operator has a higher priority than the &&
operator, so this line:
if(0 && (a++)==0)
is treated like this:
if( 0 && ((a++)==0) )
So the whole expression under the if
is false, and a++
is not even evaluated due to short circuitry of the &&
operator.
You can read about Operator Precedence and Associativity on cppreference.com.
When in doubt, you should use parenthesis to express your intention clearly. In this case, it should be:
if( (0 && (a++)) == 0 )
Though, it does not make any sense, as it always evaluates to true
and a++
is not incremented here, either.