Блог пользователя Tomg

Автор Tomg, история, 3 года назад, По-английски

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.

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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.