www.
linuxforu.
com | LINUX FOR YOU | JUNE 2007
C M Y K
87
I
n my previous column, we saw some of the pitfalls of using
+ and – operators to swap two variables without using a
temporary variable:
*i = *i + *j;
*j = *i - *j;
*i = *i - *j;
Think about the...
More

www.
linuxforu.
com | LINUX FOR YOU | JUNE 2007
C M Y K
87
I
n my previous column, we saw some of the pitfalls of using
+ and – operators to swap two variables without using a
temporary variable:
*i = *i + *j;
*j = *i - *j;
*i = *i - *j;
Think about the logic in using + and – for such
swapping.
Can we use any other operators for a
similar purpose? Yes, * and / are complementary
operators and they can be used for such swapping as
well, following the same logic:
*i = *i * *j;
*j = *i / *j;
*i = *i / *j;
It works.
However, this solution has two
problems: if i and j are big, then *i * *j will overflow
and by using the division operation you can’t get the
original values back; and if *j is 0, the *i / *j
expression will result in a divide by zero exception.
What about the two complementary bit-wise
operators & and | .
.
.
can we use them for swapping by
following similar logic?
*i = *i & *j;
*j = *i | *j;
*i = *i | *j;
No, it doesn’t work.
Unlike + and *, the & operator is not
really an
Less