Why is “a^=b^=a^=b;” different from “a^=b; b^=a; a^=b;”?

前端 未结 6 1067
梦如初夏
梦如初夏 2020-12-05 14:53

I tried some code to swap two integers in Java without using a 3rd variable, using XOR.

Here are the two swap functions I tried:

package lang.numeric         


        
6条回答
  •  无人及你
    2020-12-05 15:05

    I do not have enough reputation points to comment on Nathan's answer.

    @Nathan Hughes response talking about the Java Puzzlers book is spot on, and his answer points to some insights that does allow you to do this in 1 line. Though not as elegantly as the OP's question.

    As Nathan points out:

    In the CleverSwap program, the variable x is sampled twice—once for each appearance in the expression—but both samplings occur before any assignments

    As well as using https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html as a guide, you can do this in 1 line with:

    a = ( b = (a = a ^ b) ^ b) ^ a;
    

    The key being the assignment of the a variable value as part of the first XOR ensuring that you keep that on the left side of the second XOR (see the jls link above, for a good example of assignment in the left hand operand). Similarly, setting the b variable with the results of the second XOR, again keeping to the left of the final XOR.

提交回复
热议问题