Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,693 questions

57,001 answers

573 users

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

...