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?

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 …

## All 3 Replies

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.

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 `-`.

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 *=.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.