Possible Duplicate:
Swapping two variable value without using 3rd variable
I came across this code on Quora. For C:
a^=b^=a^=b;
For Ruby/Python:
a,b=b,a
Possible Duplicate:
Swapping two variable value without using 3rd variable
I came across this code on Quora. For C:
a^=b^=a^=b;
For Ruby/Python:
a,b=b,a
The C example is using a couple of silly tricks to swap the two numbers, which you can read about in this identical question.
The Ruby/Python example is using tuple unpacking, which is much more sensible/readable.
More detail:
C: This is a variant of the much vaunted swap without a third variable, but it is not readable, has undefined behaviour (as Kirilenko points out) and is generally a bad idea. The integer version has overflow issues to boot. In C++, just use std::swap(a,b)
, because that just works. One thing to be very careful of when writing swapping methods is that you might be passed the same thing twice, particularly if you're using references or pointers in C.
Ruby/Python: a tuple is constructed with the values of a and b, and the assignment to a comma-separated list of variables is interpreted by splitting up the anonymous tuple and assigning the individual variable values. This method does use a 'third variable', namely the anonymous tuple.
a ^= b ^= a ^=b;
^
is the binary XOR operator. Note that this code has an undefined behavior: the values of a
and b
are modified twice between two sequence points.