dev-resources.site
for different kinds of informations.
Swapping Numbers Without a Temporary Variable in C using XOR like a pro.
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;
Featured ones: