Possible Duplicate:
Swapping two variable value without using 3rd variable
we have int a=4; int b=7;
can i swap these no.s without using third variable
Possible Duplicate:
Swapping two variable value without using 3rd variable
we have int a=4; int b=7;
can i swap these no.s without using third variable
The precise implementation of course depends on the programming language you're using, but check out XOR swap.
An example in C could be
#include <stdio.h>
/* Swaps the content pointed to by a and b. The memory pointed to is
assumed non-overlapping! */
void swap(int* a, int* b)
{
*a = (*a)^(*b);
*b = (*a)^(*b);
*a = (*a)^(*b);
}
int main(int argc, char** argv)
{
int a = 4;
int b = 7;
printf("a=%d, b=%d\n", a, b);
swap(&a, &b);
printf("a=%d, b=%d\n", a, b);
return 0;
}
Important: As Prasoon Saurav commented on the question itself, this answer to another question is more correct than mine, seeing as it is important that the two variables reside at non-overlapping locations in memory. My example does not check for this.