Swapping the values of two variables without using a temporary variable is a classic programming problem. One elegant solution to this problem in C involves using bitwise XOR operations.
Algorithm
Consider two variables a
and b
. The goal is to swap their values.
Initialize
a
andb
with the values to be swapped.-
Perform the following steps:
a ^= b; b ^= a; a ^= b;
Explanation
Let's break down the algorithm step by step:
a ^= b;
: XOR (^=
)a
withb
and store the result back ina
. After this operation,a
contains the result ofa XOR b
.b ^= a;
: XORb
with the new value ofa
(which was the original value ofb
). After this operation,b
contains the result ofb XOR (a XOR b)
, which simplifies toa
.a ^= b;
: XORa
with the new value ofb
(which was the original value ofa
). After this operation,a
contains the result of(a XOR b) XOR a
, which simplifies tob
.
Now, a
holds the original value of b
and b
holds the original value of a
, effectively swapping their values without using a temporary variable.
Example
Consider the following example:
int a = 5, b = 7;
a ^= b;
b ^= a;
a ^= b;
Top comments (3)
You neglected to say why you'd want to do this. "Without using a temporary" isn't a goal. Is using XOR actually more performant? Did you profile it?
Swapping variable with XOR is a classic programming trick.
Regarding performance, XOR swapping is often considered more efficient than using a temporary variable because it involves only three bitwise XOR operations, which are typically faster than assignment operations and memory accesses involved in using a temporary variable.
Yes, I know about XOR. I gave my comment to point out that you don't tell the reader in general as part of your article why you'd do it.
That aside, unless it's part of a hot-code path, it doesn't matter. You should always profile before doing (premature) optimization.