Possible Duplicate:
What is the fastest way to swap values in C?
How can I swap the values of two variables without using 3rd variable?
I want to swap (interchange) the values of two variables a
and b
.
Possible Duplicate:
What is the fastest way to swap values in C?
How can I swap the values of two variables without using 3rd variable?
I want to swap (interchange) the values of two variables a
and b
.
Typically, you don't. There's no reason not to use a third variable, just call std::swap(a, b)
and move on with your life.
With integer types, you can do:
void swap(int& a, int& b)
{
if (a != b)
{
a ^= b;
b ^= a;
a ^= b;
}
}
But this typically gives worse performance than just using a third variable.
You're referring to a pretty famous riddle. The answer depends on the data type. There is no algorithm for a generic type.
https://en.wikipedia.org/wiki/XOR_swap_algorithm
void xorSwap (int *x, int *y) {
if (x != y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
Unless you can use processor-specific instructions that do the exchange without a third variable, you will have to use a temporary to do the swap, sorry.
You could use std::swap
but that only hides the temporary.
There's a couple ways you can do it. You can swap the pointers, or if the values are integers, you can use a little arithmetic hack:
a=a+b;
b=a-b;
a=a-b;
You could use the XOR swap algorithm
a = a^b;
b = b^a;
a = a^b;
However, this is not a great idea. Also from wikipedia:
Most modern compilers can optimize away the temporary variable in the naive swap, in which case the naive swap uses the same amount of memory and the same number of registers as the XOR swap and is at least as fast, and often faster.[cite] The XOR swap is also much less readable, and can be completely opaque to anyone who isn't already familiar with the technique.