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
.
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
.
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 asx = x + y
, however it actually isx = <current value of x> + y
. This it does matter in chained assignments. Compare the chainedx += y += x += y
to breaking it down into the same steps
This shows the difference, where the the chained compound assignment the start is
which gets resolved as
Thus even more succinctly this can be demonstrated as
Thus the result of
a ^= b ^= a ^= b
is zero, sinceb ^= a ^= b
returns the same value asa
and XOR on the same value is always zero.