isasto
isasto

Reputation: 79

Order Precedence || Order of Operations

I was working through some code in the classroom and came across the following:

int x 14; 
int y 3; 

x = x-- % y--'

The result after compiling is 'x = 2 ' 'y = 2'

I am having a very difficult time understanding the order or operations for this particular scenario. My logic based off of Oracles Operators Precedence (Here) http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Would conclude: x = (x = x -1 ) % ( y = y - 1) (because of order precedence)

Therefore: x = 13 % 2

x = 1

y = 2

I am wrong please tell me why. I have horse blinders on. Thanks in advance.

Upvotes: 4

Views: 124

Answers (3)

khelwood
khelwood

Reputation: 59113

This:

int x = 2;
println(x--);

prints 2 but leaves x at 1. Suffix increment and decrement give you the value before the variable is altered.

This:

int x = 2;
println(--x);

prints 1 and leaves x at 1. Prefix increment and decrement give you the value after the variable is altered.

EDIT:

If you assign to x in the same expression, the assignment happens last.

int x = 3;
x = 2*(x--);

The value of x-- is 3 (the value before x is decremented). So after the assignment, x ends up with the value 6 in this case.

So for your example:

int x = 14;
int y = 3;

x = x-- % y--;

The value of x-- is 14 (the value before x is decremented). The value of y-- is 3 (the value before y is decremented). So x gets assigned to 14%3==2. y is left at its decremented value, 2.

Upvotes: 4

Krayo
Krayo

Reputation: 2510

I think this happens:

int temp = (x % y);
x--;
y--;
x = temp;

Upvotes: 0

Nicolas Albert
Nicolas Albert

Reputation: 2596

x-- return x and decrease after.

x = 14, y = 3
x = 14 % 3 → 2,  (x = x - 1 → 13 is done before the x receive  14 % 3 → 2)
y = y - 1 → 2

--x decrease and return x

Upvotes: 0

Related Questions