The increment operator with parentheses

• 07-03-2011, 08:43 PM
357mag
The increment operator with parentheses
Look at this:

Code:

```x = 10 y = 2 z = x++ - (x * y)```
What I first did was do what was in parentheses first (cuz that's what we're taught), since parentheses have higher precedence than the ++ operator. So first I multiplied
(10 * 2) to get 20. Then I plugged 10 in for x and thought it would evaluate to
z = 10 - 20 which would result in -10 (final value of x would be 11 after this statement executed.)

But I got it wrong. I guess the proper way to handle this is first increment x from 10 to 11. Then plug the new value 11 in where x is in the parentheses so you now have
z = 10 - (11 * 2) which results in -12.

I don't quite follow. Why doesn't the compiler first evaluate what is in parentheses? Since parentheses have a higher order of precedence anyway it seems to me the compiler would first multiply 10 * 2 to get 20.
• 07-03-2011, 08:57 PM
Norm
Personally I would never write code where there can be a confusion over what happens first.
Break the statement up into separate statement that are understandable and easy to follow.
• 07-03-2011, 08:58 PM
Fubarable
• Precedence rules matter when two operators share the same operand.
• Order of evaluation. In Java, the left operand is always evaluated before the right operand. Also applies to function arguments.
• The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated

see: 15.7.1 Evaluate Left-Hand Operand First

But I agree with Norm: that code should be taken out back and shot.