# Thread: The increment operator with parentheses

1. Member
Join Date
May 2010
Posts
38
Rep Power
0

## The increment operator with parentheses

Look at this:

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

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

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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•