Results 1 to 3 of 3
- 07-03-2011, 07:43 PM #1Member
- Join Date
- May 2010
- Rep Power
The increment operator with parentheses
Look at this:
x = 10 y = 2 z = x++ - (x * y)
(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, 07:57 PM #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.
- By msa0127a in forum New To JavaReplies: 9Last Post: 10-05-2010, 10:37 PM
- By adhoc334 in forum Advanced JavaReplies: 5Last Post: 08-18-2010, 08:05 PM
- By abimaran in forum New To JavaReplies: 10Last Post: 11-03-2009, 05:45 PM
- By rhm54 in forum New To JavaReplies: 2Last Post: 06-14-2008, 02:57 AM