Possible Duplicate:
How does XOR variable swapping work?
Swap the values of two variables without using third variable
How can I write a C code to swap 2 integer variables without using any extra variable?
Possible Duplicate:
How does XOR variable swapping work?
Swap the values of two variables without using third variable
How can I write a C code to swap 2 integer variables without using any extra variable?
a = a^b;
b = a^b;
a = a^b;
use XOR ( ^ ) operator
you can do it with adding:
x = x + y;
y = x - y;
x = x - y;
but I think XOR is the best way because it's faster.
This is a bitwise operator like &
and |
.
1^1 == 0
0^0 == 0
1^0 == 1
0^1 == 1
You can read this for more information
a = a^b;
b = a^b;
a = a^b;
Just use XOR operator for your purposes. Just for explanation
XOR (Exclusive Or) This operation is performed between two bits (a and b). The result is 1 if either one of the two bits is 1, but not in the case that both are. There for, if neither or both of them are equal to 1 the result is 0.
For example
a=5; //011
b=6; //100
a = a^b; //a=111
b = a^b; //b=011
a = a^b; //a=100