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.
I don't think you can. Why would you not want to use a 3rd variable?
You're referring to a pretty famous riddle. The answer depends on the data type. There is no algorithm for a generic type.
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.
http://en.wikipedia.org/wiki/XOR_swap_algorithm
void xorSwap (int *x, int *y) {
if (x != y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
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.
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.
There are many ways. just Google your question and you'll find many answers.
Using Sum: (fails on large numbers)
a = a + b;
b = a - b;
a = a - b;
Using Multiply (not always working):
a = a * b;
b = a / b;
a = a / b;
Using XOR:
a = a ^ b;
b = a ^ b;
a = a ^ b;
Using ASM Code:
__asm
{
mov EAX,b
push EAX
mov EAX,a
mov b,EAX
pop EAX
mov a,EAX
}
but I suggest you to use std::swap.
Generally, you will need a third, empty variable for swapping the content of two other variables.
However, there are special cases. Here's one special swap for two bool variables a and b:
void swap_bools(bool &a, bool &b)
{
if (a != b)
{
a = !a, b = !b;
}
}