Tomg's blog

By Tomg, history, 3 years ago, In English

In Java, why is it that the code a^=b^=a^=b does not swap the values of a and b, while in C++, such code works? For example if a=1, and b=5, in Java, after doing a^=b^=a^=b, a=0, b=1.

  • Vote: I like it
  • +10
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This expression is expanded into a = a ^ (b = b ^ (a = a ^ b)); then the left-hand operand is evaluated first which results in the first a after = not getting "updated" after the innermost ^= as you are probably expecting.