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

前端 未结 6 1069
梦如初夏
梦如初夏 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:17

    Because a ^= b ^= a ^= b; is parsed like:

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

    Which can be reduced to:

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

    So b will have the value b ^ (a ^ b) and finally a will be a ^ (b ^ (a ^ b).

提交回复
热议问题