DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
vycoder profile image
yev • Edited
x ^= y;
y ^= x;
x ^= y;
Collapse
 
dean profile image
dean • Edited
x := 5
y := 5
swap(&x, &y)
fmt.Println(x, y) // uh oh, they are both zero!
Collapse
 
vycoder profile image
yev

I've written my answer with C in mind, and it does explain how it works if you try the calculation by hand: onlinegdb.com/B1IY6hFK7

#include <stdio.h>

int main()
{
    int a = 77;
    int b = 42;
    printf("a: %d, b: %d \n", a, b);

    swap(&a, &b);
    printf("after swap \n");
    printf("a: %d, b: %d", a, b);

    return 0;
}

void swap(int *a, int *b) {
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

When both a and b has the same value: onlinegdb.com/r1WeypFF7

Result may vary depending on the language compiler, you might have to adjust the snippet according to your language's nuances.