Spark
Spark

Reputation: 216

Why does (0 && 1 == 0) not evaluate to true?

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);

Upvotes: 7

Views: 1738

Answers (3)

jsl
jsl

Reputation: 1

Although the question seems easy it's very error-prone. We need to know the precedence of various operators involved in this.

1. postfix (++)
2. ==
3. Logical AND (&&)

the final expression can be seen as: if ( (0 && (a++)) == 0 ) which is true. Hence statement under if is evaluated to be true.

Upvotes: -1

Slava
Slava

Reputation: 44238

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.

Upvotes: 23

Karen Baghdasaryan
Karen Baghdasaryan

Reputation: 2271

As already mentioned, the precedence of == is higher than precedence of &&, so the statement is resolved into

if( 0 && ((a++)==0))

However, still even if you add the correct order of brackets, a++ returns the original value of a, which is 0, but the a is incremented. If you want to return the updated value of a, you should write ++a

if( ((++a) && 0) == 0  )

Upvotes: 5

Related Questions