Interesting XOR expression evaluation in javascript

55 views Asked by At

Tried out the expression a ^= b ^= a ^= b with a and b taking values 3 and 5 respectively. When executed in Javascript the answer is a = 0 and b = 5, but when run in C the variables got reversed to a = 5 and b = 3.

Executed in browser Executed in C playground

1

There are 1 answers

0
VLAZ On

In compound assignment operations, the value of the assignee is evaluated once.

This does not make a difference for simple expression like x += y and the result is the same as x = x + y, however it actually is x = <current value of x> + y. This it does matter in chained assignments. Compare the chained x += y += x += y

let x = 1;
let y = 1;

x += y += x += y;

console.log(`x = ${x} y = ${y}`);

to breaking it down into the same steps

let x = 1;
let y = 1;

x += y
y += x
x += y;

console.log(`x = ${x} y = ${y}`);

This shows the difference, where the the chained compound assignment the start is

x += <expression>

which gets resolved as

x = 1 + <expression>
//  ^ current value of x

Thus even more succinctly this can be demonstrated as

let x = 1;

x += x = 7;

console.log(x); // 1 + 7 = 8

Thus the result of a ^= b ^= a ^= b is zero, since b ^= a ^= b returns the same value as a and XOR on the same value is always zero.

a = 3 dec = 011 bin;
b = 5 dec = 101 bin;

a ^= b ^= a ^= b

a = 011 bin ^ (b ^= a ^= b)
a = 011 bin ^ (b = (101 bin^ (a ^= b)))
a = 011 bin ^ (b = (101 bin ^ (a = (011 bin^ b))))

a = 011 bin ^ (b = (101 bin ^ (a = (011 bin ^ 101 bin))))
a = 011 bin ^ (b = (101 bin ^ (a = 110 bin)))
a = 011 bin ^ (b = (101 bin ^ 110 bin))
a = 011 bin ^ (b = 011 bin)
a = 011 bin ^ 011 bin
a = 000 bin