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

前端 未结 14 769
误落风尘
误落风尘 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 22:04

    Consider this other, maybe simpler example:

    int x = 1;
    System.out.println(x == ++x); // false
    x = 1; // reset
    System.out.println(++x == x); // true
    

    Here, the pre-increment operator in ++x must be applied before the comparison is made — just like (x = y) in your example must be calculated before the comparison.

    However, expression evaluation still happens left → to → right, so the first comparison is actually 1 == 2 while the second is 2 == 2.
    The same thing happens in your example.

提交回复
热议问题