102 june 2008 | LInuX For You | www.
openITis.
com
T
he following trick using three consecutive ex-or
operations for swapping two variables without
using a temporary is well known and particularly
popular among students:
i ^= j; j ^= i; i ^= j;
Here, i...
More
102 june 2008 | LInuX For You | www.
openITis.
com
T
he following trick using three consecutive ex-or
operations for swapping two variables without
using a temporary is well known and particularly
popular among students:
i ^= j; j ^= i; i ^= j;
Here, i and j are integer variables and it works well
(we covered a few pitfalls earlier with this).
For further
optimisation, one often sees this solution combining the
three statements into a single statement:
i ^= (j ^= (i ^= j));
Try this with your favourite C compiler; it usually
works.
This trick works based on the following
assumption: the values of i and j are modified in the RHS
(right-hand side) of the expression and the modified
values are expected to be used in the LHS (left-hand side)
of the expression.
However, this solution need not work and the updated
values of i and j need not get reflected when read
again.
This is because the compiler is free to optimise
the sequence of reads and writes, using temporaries
internally.
Less