Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

Expression - How

susan waters
Ranch Hand
Posts: 68
can anybody explain me how it print -9?

thanks
[ July 19, 2006: Message edited by: Barry Gaunt ]

Sheriff
Posts: 14691
16
You've got to understand the priority of each symbol, and put brackets around them:
x -= ( (1 < 0)?2:4 );

1 < 0 ? No -> 4
x = x - 4
x = -9

Here is nice table illustrating operators precedence:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html

You'll notice that -= is lower than "? :"
[ July 18, 2006: Message edited by: Satou kurinosuke ]

Keith Lynn
Ranch Hand
Posts: 2409
The expression 1 < 0 ? 2 : 4 is an expression whose value is 2 if the condition is true, and 4 if the condition is false.

Since the condition is false, the value of the expression is 4.

x is -5.

When you execute the line x -= 1 < 0 ? 2 : 4, that is like saying x -= 4, so x is -9.
[ July 19, 2006: Message edited by: Barry Gaunt ]