This equation swaps two numbers without a temporary variable, but uses arithmetic operations:
a = (a+b) - (b=a);
How can I do it without arithmetic operations? I was thinking with XOR
This equation swaps two numbers without a temporary variable, but uses arithmetic operations:
a = (a+b) - (b=a);
How can I do it without arithmetic operations? I was thinking with XOR
http://en.wikipedia.org/wiki/XOR_swap_algorithm
Note: Don't use this unless you absolutely have to (i.e. you are writing hyper-optimised assembler). The article gives some reasons why not.
In C this should work:
a = a^b;
b = a^b;
a = a^b;
OR a cooler/geekier looking:
a^=b;
b^=a;
a^=b;
For more details look into [1]. XOR is a very powerful operation that has many interesting usages cropping up here and there.
The best way to swap two numbers without using any temporary storage or arithmetic operations is to load both variables into registers, and then use the registers the other way around!
You can't do that directly from C, but the compiler is probably quite capable of working it out for you (at least, if optimisation is enabled) - if you write simple, obvious code, such as that which KennyTM suggested in his comment.
e.g.
void swap_tmp(unsigned int *p)
{
unsigned int tmp;
tmp = p[0];
p[0] = p[1];
p[1] = tmp;
}
compiled with gcc 4.3.2 with the -O2
optimisation flag gives:
swap_tmp:
pushl %ebp ; (prologue)
movl %esp, %ebp ; (prologue)
movl 8(%ebp), %eax ; EAX = p
movl (%eax), %ecx ; ECX = p[0]
movl 4(%eax), %edx ; EDX = p[1]
movl %ecx, 4(%eax) ; p[1] = ECX
movl %edx, (%eax) ; p[0] = EDX
popl %ebp ; (epilogue)
ret ; (epilogue)
Just use something else, e.g. a variable that's not a temporary. For instance,
int main (int argc, char** argv) {
int a = 5; int b = 6;
argc = a; a = b; b = argc;
}
After all, the point of the question is not to show the sane way to do it (c=a;a=b;b=c
). It's to show you can think out of the box, or at least copy the answer of someone else who can.