Consider the following statement. What will be the value stored in b?
int a=1;
int b = a+=1 ? a+=1 : 10;
I get the answer as 4. Can anyone explain how that works please.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It has to do with precedence. If you examine the following code (with the rightmost
a+=1changed for simplicity):you will see that the output is
8, not7or10.That’s because the statement:
is being interpreted as:
Now, applying that to your case, we get:
and, in order of execution:
a += 1(since1is true) setsato2.a += 2(2is the result of the previous step) setsato4.b = 4(4is the result of the previous step).Just keep in mind that you can’t necessarily rely on that order of evaluation. Even though there is a sequence point at the
?(so that1is evaluated fully before continuing), there is no sequence point between the rightmosta += ...and the leftmosta += .... And modifying a single variable twice without an intervening sequence point is undefined behaviour, which is whygcc -Wallwill give you the very useful message:That fact that it gives you
4is pure coincidence. It could just as easily give you3,65535or even format your hard disk to teach you a lesson 🙂