Is anything terribly wrong with the code?
Yes!
a^=b^=a^=b
in fact invokes Undefined Behaviour in C and in C++ because you are trying to change the value of a
more than once between two sequence points.
Try writing (although not foolproof )
a ^= b;
b ^= a;
a ^= b;
instead of a^=b^=a^=b
.
P.S : Never try to swap the values of two variables without using a third one. Always use a third variable.
EDIT :
As @caf noticed b^=a^=b
is fine even though the order of evaluation of arguments of ^=
operator is unspecified, since all the accesses of b
within the expression are being used to compute the final value that is being stored in b
, the behaviour is well defined.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…