DEV Community

Seamoon Pandey
Seamoon Pandey

Posted on

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.

  1. Initialize a and b with the values to be swapped.

  2. Perform the following steps:

    a ^= b;
    b ^= a;
    a ^= b;
    

Explanation

Let's break down the algorithm step by step:

  • a ^= b;: XOR (^=) a with b and store the result back in a. After this operation, a contains the result of a XOR b.

  • b ^= a;: XOR b with the new value of a (which was the original value of b). After this operation, b contains the result of b XOR (a XOR b), which simplifies to a.

  • a ^= b;: XOR a with the new value of b (which was the original value of a). After this operation, a contains the result of (a XOR b) XOR a, which simplifies to b.

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;
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
pauljlucas profile image
Paul J. Lucas

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?

Collapse
 
seamoonpandey profile image
Seamoon Pandey

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.

Collapse
 
pauljlucas profile image
Paul J. Lucas

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.