sri.vatsa sri.vatsa - 1 year ago 110
C Question

Assignment operators in if statement

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

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download