How does XOR work for swapping values in C

1 Answer

0 votes
// The XOR swap trick is a classic bitwise technique that
// swaps two variables without using a temporary variable. 

#include <stdio.h>

/**
 * @brief Swap two integers using the XOR swap algorithm.
 *
 * The XOR swap algorithm exchanges two integer values without using
 * a temporary variable.
 *
 * XOR properties used:
 *   x ^ x = 0
 *   x ^ 0 = x
 *   x ^ y ^ y = x
 *
 * WARNING:
 * If both pointers reference the same memory location, the XOR algorithm
 * would corrupt the value. Therefore, we explicitly guard against that case.
 *
 * @param a Pointer to the first integer.
 * @param b Pointer to the second integer.
 */
void xor_swap(int *a, int *b)
{
    if (a == NULL || b == NULL) {
        return;
    }

    /* Prevent self-swap */
    if (a == b) {
        return;
    }

    *a ^= *b; /* 0101 ^ 1010 = 1111 = 15 */ 
    *b ^= *a; /* 1010 ^ 1111 = 0101 =  5 */
    *a ^= *b; /* 1111 ^ 0101 = 1010 = 10 */
}

int main(void)
{
    int x = 5;
    int y = 10;

    printf("Before swap: x = %d, y = %d\n", x, y);

    xor_swap(&x, &y);

    printf("After swap:  x = %d, y = %d\n", x, y);

    return 0;
}


/*
run:

Before swap: x = 5, y = 10
After swap:  x = 10, y = 5

*/

 



answered Sep 29 by avibootz
edited Sep 29 by avibootz

Related questions

...