How to Switch the Values of Two Variables Without Using a Temporary Variable
In programming, there are many times that you need to switch two variable values (such as in a Bubble Sort). Most people would show you how to do it with three variables and use wasteful operations, but I can show you how to do it with two...EFFICIENTLY!
Instructions
-
-
1
Understanding XOR:
XOR or Exclusive-Or, is similar to the commonly used INCLUSIVE-Or, except that if both inputs are 1, the output is 0 (as opposed to INCLUSIVE-Or where the value is 1).
This addresses this case where we normally do something like:
int ii1 = 1;
int ii2 = 2;
int tmp;tmp = ii1;
ii1 = ii2;
ii2 = tmp; -
2
Now, the magic:
A triple XOR performed on two variables will SWITCH THEM!!!
So, in C#:
int ii1 = 1;
int ii2 = 2;ii1 ^= ii2;
ii2 ^= ii1;
ii1 ^= ii2;The variables have now been swapped without using a temporary variable!
-
-
1
Tips & Warnings
Binary operations are usually VERY efficient.
Be sure to perform your xor operations in the correct order.
The ^ (circumflex or caret) is commonly the XOR operation, but check to make sure what it is in the programming language that you use (^ in C++, C#, Java and PHP, xor in Pascal, Xor in VB.NET, etc)
Comments
-
Ray Ray
Jun 24, 2008
Nice article! keep posting