In C and C++ you need to be careful when using pre and post increment operators in this way.
The 'strange behaviour' is because there are several manipulations being applied to the same variable on a single line, including a pre/post-increment operation, which isn't evaluated in the way you'd think.
Typically pre/post increment operations should be the only manipulation performed on a single variable in any given line..... If that makes sense?! Otherwise you need to be really careful!
For anybody who doesn't know about the pre and post increment operators in C/C++ (and Java):
The pre-increment operator ++n sets the value of n to n+1 and returns the resultant value of n+1.
Whereas the post-increment operator n++ sets the value of n to n+1 but returns the original value of n. Java implements the same behaviour for these operators.
So in your pre-increment example:
int a=4;
a += a * 2 +(++a);
Logically you would expect to see the same evaluation as the java example:
a += 4*2+(++4)
Therefore you would expect the new value of a to be evaluated like this:
a = 4 + 8 + 5
a = 17
But in C++, this is not the case. So how are we getting to 18?
Here's the reason:
According to the rules of precedence in C++; the multiplication operation has greater precedence, so it is the first operation that is performed. Then the pre-increment occurs (which modifies the value of the variable), and the addition is performed last.
So in your pre-increment example, given that the initial value of a is 4, you get this:
a += a * 2 + (++a)
First operation is a*2. Value of a is 4, therefore a*2=8.
Substitute that into the example:
a += 8 + (++a)
then the pre-increment is performed giving:
a += 8 + 5
NOTE: the value of a is now 5.
Finally the addition is performed, yielding this:
5 += 8 + 5
Therefore a=18.
The same applies to the post-increment example.
Again, assuming the initial value of a is 4:
a += a*2+(a++);
The multiplication is performed first yielding:
a+=8+(a++)
Then the increment:
a += 8 + 4
Note: In the above, the post increment sets the value of a to 5 and returns the original value of a (which was 4).
Yielding this for the final addition:
5 += 8 + 4
Therefore a = 17.
Clear?
