Why is x == (x = y) not the same as (x = y) == x?

前端 未结 14 961
误落风尘
误落风尘 2021-01-29 21:11

Consider the following example:

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

        System.out.println(x =         


        
14条回答
  •  一整个雨季
    2021-01-29 21:56

    Expressions are evaluated from left to right. In this case:

    int x = 1;
    int y = 3;
    

    x == (x = y)) // false
    x ==    t
    
    - left x = 1
    - let t = (x = y) => x = 3
    - x == (x = y)
      x == t
      1 == 3 //false
    

    (x = y) == x); // true
       t    == x
    
    - left (x = y) => x = 3
               t    =      3 
    -  (x = y) == x
    -     t    == x
    -     3    == 3 //true
    

提交回复
热议问题