Java executes arithmetic Expression wrong? -


i don`t understand how java progressing arithmetic expression

int x = 1; int y = 1; x += y += x += y; system.out.println("x=" + x + " y=" + y); 

with java x = 4 , y = 3. in c, perl, php x=5 , y = 3 on paper x = 5 , y = 3

this nasty part, obviously:

x += y += x += y; 

this executed as:

int originalx = x; // used later x = x + y; // right-most x += y y = y + x; // result of "x += y" value stored in x x = originalx + y; // result of "y += x" value stored in y 

so:

                     x      y (start)              1      1 x = x + y            2      1 y = y + x            2      3 x = originalx + y    4      3 

the important part use of originalx here. compound assignment treated as:

x = x + y 

and first operand of + evaluated before second operand... why takes original value of x, not "latest" one.

from jls section 15.16.2:

if left-hand operand expression not array access expression, then:

  • first, left-hand operand evaluated produce variable. if evaluation completes abruptly, assignment expression completes abruptly same reason; right-hand operand not evaluated , no assignment occurs.

  • otherwise, value of left-hand operand saved , right-hand operand evaluated. if evaluation completes abruptly, assignment expression completes abruptly same reason , no assignment occurs.

when in doubt, consult language specification - , never assume because 2 languages behave differently, 1 of them "wrong". long actual behaviour matches specified behaviour each language, - mean need understand behaviour of each language work with, of course.

that said, should avoid horrible code in first place.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -