Logo

dev-resources.site

for different kinds of informations.

Swapping Numbers Without a Temporary Variable in C using XOR like a pro.

Published at
2/22/2024
Categories
c
swapping
swap
Author
seamoonpandey
Categories
3 categories in total
c
open
swapping
open
swap
open
Author
13 person written this
seamoonpandey
open
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

Featured ones: