Search code examples
javascriptc++swapxor

Why single-line XOR swap doesn't work in Javascript but works in C++?


In javascript, if I write:

var a = 6;
var b = 4;
a ^= b ^= a ^= b;
console.log(a, b);

the result will be 0 6.
but if I write:

var a = 6;
var b = 4;
a ^= b;
b ^= a; 
a ^= b;
console.log(a, b);

the result will be 4 6. And it's correct.

Why this single-line way of XOR swapping in javascript does not work?
And why it works fine in C++?


Solution

  • In JavaScript, expressions are evaluated left-to-right.

    That means that your one-liner is evaluated like this:

       a ^= b ^= a ^= b;
    => a = a ^ (b = b ^ (a = a ^ b))
    => a = 6 ^ (b = 4 ^ (a = 6 ^ 4))
    => a = 6 ^ (b = 4 ^ 2)
    => a = 6 ^ 6 = 0
       b = 4 ^ 2 = 6
    

    In C++, you're making unordered modifications to the same object so the program is undefined.

    The moral of this is that clever code rarely is.