We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,134 Members — Technology Publication meets Social Media

# Int post-increment help

I'm going over a practice exam right now and I've come across something I can't figure out. I understand what incrementing is but I just don't know why the answer is 0.

``````//What is the value of a after the following code is run (int a=12).

a += a -= a *= a;
``````

I understand that a += a is 24 which is not my problem. When I run a cout after each incrament i get each a value equal to 24,0,0. How does a get from 24 to zero? Thats what im confused about.

Is it becuase its 12 + 12 = 24 - 24 = 0 * 0 = 0?

2
Contributors
3
Replies
3 Hours
Discussion Span
1 Year Ago
Last Updated
4
Views
pattmorter
Light Poster
41 posts since Feb 2012
Reputation Points: 10
Skill Endorsements: 0

http://en.cppreference.com/w/cpp/language/operator_precedence

You have a complex statement, Break it up into smaller statements using the order of precedence. It's an easy question. You'll get a is 0 even if you screw up the order of precedence.

You have three statements, not necessarily in this order. Study the order of precedence and stick them in the right order;

``````a += a;
a -= a;
a *= a;
``````

Look at the the middle one.

``````a -= a;
``````

It's the same as

``````a = 0;
``````

So change to

``````a += a;
a = 0;
a *= a;
``````

Now stick them in the right order. Or don't bother. Convince yourself that it's going to end up with a being 0 no matter what order you put them in and no matter what a's initial value is.

VernonDozier
Posting Expert
5,675 posts since Jan 2008
Reputation Points: 2,633
Skill Endorsements: 18

I neve thought about thinking `a -= a;` in that manor but that would make sense. Thanks a lot. I just need to remember that `* / %` comes before `+` and `-`.

pattmorter
Light Poster
41 posts since Feb 2012
Reputation Points: 10
Skill Endorsements: 0

You're welcome.

I just need to remember that * / % comes before + and -.

True, but irrelevant to this particular problem. You aren't dealing with *, +, -, where * takes precedence. You're dealing with *=, -=, +=, which all have the same precedence and evaluate right to left, so "a *= a += a" is going to be

``````    a += a;
a *= a;
``````

since += is to the right of *=.

VernonDozier
Posting Expert
5,675 posts since Jan 2008
Reputation Points: 2,633