Saturday, February 5, 2011

XOR Swap Algorithm

XOR swap algorithm is a nifty little trick to swap two variables with each other without a temporary variable.

Here is a little snippet of code showing how it works:

#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
int x, y;

x = 123;
y = 456;

cout << "x = " << x << endl; // x = 123
cout << "y = " << y << endl; // y = 456
cout << endl;

// Swap values
x ^= y;
y ^= x;
x ^= y;

cout << "x = " << x << endl; // x = 456
cout << "y = " << y << endl; // y = 123

return 0;
}

No comments:

Post a Comment