CAj0n.
CAj0n.

Reputation: 25

Assignment operators in if statement

int a = 0, b = 0, c = -1;

if (b = a || b == ++c )
    a+=3;

Why are the values of a,b and c 3 , 1, 0 respectively? More specifically, why is b 1 and not 0?

Upvotes: 0

Views: 80

Answers (2)

asad_hussain
asad_hussain

Reputation: 2001

Once you are clear with the precedence of operators,it will be easy for you to tackle such type of questions.Go through this to know about operator precedence in C.

You should see my answer after going through the precedence list because then it will get more easily inside your mind.

Now,coming to your question....

Out of all the operators used in the above code, ++c has the highest precedence.So the value of c becomes 0 and then value of c is compared to value of b here b == ++c which evaluates to true i.e 1 and now || of 1 and a is taken which is 1.

And finally this result 1 is assigned to b.So the overall execution of if statement evaluates to true and value of a is incremented by 3.

Hence finally the value of a=3,b=1 and c=0.

Upvotes: 0

Barmar
Barmar

Reputation: 780984

Because || has higher precedence than =, so it's being parsed as if you'd written.

if (b = (a || (b == ++c)))

This calculates a || (b == ++c). This is true because b == 0 and ++c == 0, so b == ++c is true, and true is 1.

Add parentheses to get what you want:

if ((b = a) || (b == ++c))

But IMHO it's generally best to avoid writing such complex expressions. Do them as separate statements:

b = a;
if (b || b == ++c)

Upvotes: 6

Related Questions