Forum Moderators: phranque

Message Too Old, No Replies

x == (x = y) not the same as (x = y) == x? why?

         

Whopper

12:43 pm on Feb 20, 2023 (gmt 0)

Top Contributors Of The Month



Consider the below example:

class Quirky {
public static void main(String[] args) {
int x = 1;
int y = 3;

System.out.println(x == (x = y)); // false
x = 1; // reset
System.out.println((x = y) == x); // true
}
}


I am unsure if the Java Language Specification contains an entry that states that when using the assignment operator (x = y), the previous value of the variable x should be loaded for comparison before the right side (y) are evaluated.

What is causing the difference in evaluating (x = y) and (x = 3)? I thought that (x = y) would be evaluated first, and since x is equal to itself (3), the result should be accurate.
int oldX = x;
x = y;
return oldX == y;


which, being even more superficial than x86 CMPXCHG instruction, deserved a shorter expression in Java.
<snip>



[edited by: not2easy at 6:02 pm (utc) on Feb 20, 2023]
[edit reason] Please see TOS [webmasterworld.com] [/edit]

Dimitri

6:21 pm on Feb 20, 2023 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



x == (x = y)

is equivalent to

left = x ;
right = ( x = y ) ; ( after this line, "right = y" and "x=y" )
left == right ; (return false since left = x and right = y )

------------------
(x = y) == x

is equivalent to

left = ( x = y ) ; ( left = y and x = y )
right = y ;
left == right ( return true, both sides are equal to "y" )


in other words, in this case. (x = y) == x, x takes the value of y, when the left expression is evaluated , so when the right expression is evaluated x has the value of y. I am not sure i make it clear :">