Order priority || Order of operations
I was working on some code in a class and came across the following:
int x 14;
int y 3;
x = x-- % y--'
Result after compilation 'x = 2' 'y = 2'
I am having a very difficult time understanding the order or operations for this particular scenario. My logic is based on the oracle operator precedence (here) http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Would conclude: x = (x = x -1)% (y = y - 1) (due to order priority)
Therefore: x = 13% 2
x = 1
y = 2
I'm wrong, tell me why. I have horses. Thanks in advance.
source to share
It:
int x = 2;
println(x--);
prints 2, but leaves x
at 1. Incrementing the suffix and decrementing gives you the value before changing the variable.
It:
int x = 2;
println(--x);
prints 1 and leaves x
at 1. Incrementing and decreasing the prefixes gives you the value after changing the variable.
EDIT:
If you assign x
in the same expression, the assignment occurs last.
int x = 3; x = 2*(x--);
The value x--
is 3 (the value to is x
decremented). So after assignment x
ends up with a value of 6 in this case.
So for your example:
int x = 14;
int y = 3;
x = x-- % y--;
The value x--
is 14 (the value to is x
decremented). The value y--
is 3 (the value to is y
decremented). Therefore it is x
assigned 14%3==2
. y
remains with the reduced value, 2.
source to share