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

前端 未结 14 755
误落风尘
误落风尘 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:41

    The kind of question you asked is a very good question if you want to write a Java compiler, or test programs to verify that a Java compiler is working correctly. In Java, these two expressions must produce the results that you saw. In C++, for example, they don't have to - so if someone reused parts of a C++ compiler in their Java compiler, you might theoretically find that the compiler doesn't behave as it should.

    As a software developer, writing code that is readable, understandable and maintainable, both versions of your code would be considered awful. To understand what the code does, one has to know exactly how the Java language is defined. Someone who writes both Java and C++ code would shudder looking at the code. If you have to ask why a single line of code does what it does, then you should avoid that code. (I suppose and hope that the guys who answered your "why" question correctly will themselves avoid that ind of code as well).

提交回复
热议问题