Results 1 to 3 of 3
  1. #1
    357mag is offline Member
    Join Date
    May 2010
    Posts
    18
    Rep Power
    0

    Default 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. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,329
    Rep Power
    25

    Default

    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.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

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

Similar Threads

  1. matching parentheses stack
    By msa0127a in forum New To Java
    Replies: 9
    Last Post: 10-05-2010, 10:37 PM
  2. Using regex to retrieve all text inside parentheses
    By adhoc334 in forum Advanced Java
    Replies: 5
    Last Post: 08-18-2010, 08:05 PM
  3. Increment Operator Example
    By abimaran in forum New To Java
    Replies: 10
    Last Post: 11-03-2009, 04:45 PM
  4. Increment a Variable
    By rhm54 in forum New To Java
    Replies: 2
    Last Post: 06-14-2008, 02:57 AM

Posting Permissions

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