Monday, March 11, 2013

Did you know–XOR swap algorithm?

Did you know that you can use the XOR operator to swap the values in 2 variables without the use of a 3rd variable?

Check it out:

int x = 111;
int y = 3333;

x ^= y;
y ^= x;
x ^= y;

x.Dump();
y.Dump();

Outputs:

3333
111

No comments: