Why doesn't single-line XOR exchange work in Javascript, but work 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 rightly so.

Why does this one-line way to replace XOR in javascript not work?
And why does this work great in C ++?

+4
source share
1 answer

In JavaScript, expressions are evaluated from left to right.

This means that your single line file is evaluated as follows:

   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 make unordered changes for the same object, so the program is undefined.

The moral of this is that smart code rarely happens.

+6

Source: https://habr.com/ru/post/1607592/


All Articles