# swap program using 2 variable

i wonder if this is true to build a swap(interchange) program that swaps the values of 2 variables using only 2(same) variables in c or java .I ve heard its possible
perhaps for using three variables a,b,temp
code is
temp=a;
a=b;
b=temp;
just heard somewhere that its possible;)

Yes it is possible to write a swap program using just two variables, but this is true only for integral numbers and plain character variables, and not for complex types like strings, structures or classes…

This code should do:

``````a = a + b;
b = a - b;
a = a - b;
``````

Why it ain’t true for floating point numbers is binary operations on two floating point numbers are not associative (there might be some round-off errors)… I think with pointers it can become possible to do it in other datatypes too

With pointers if you swap a variable like the one I mentioned above, you would only be swapping the two pointers containing the addresses but the actual content in their memory locations would still remain the same This is not technically swapping IMO…

On 23/07/10 06:06, wormulove wrote:
>
> i wonder if this is true to build a swap(interchange) program that swaps
> the values of 2 variables using only 2(same) variables in c or java .I
> ve heard its possible
> perhaps for using three variables a,b,temp
> code is
> temp=a;
> a=b;
> b=temp;
> just heard somewhere that its possible;)
>
>

theo@ZZ9-Plural-Z-Alpha:~> python
Python 2.6.2 (r262:71600, Jun 17 2010, 13:37:18)
[GCC 4.4.1 [gcc-4_4-branch revision 150839]] on linux2
>>> a=1
>>> b=2
>>> a=a^b
>>> b=a^b
>>> a=a^b
>>> a
2
>>> b
1
>>>

‘^’ is the Python XOR function.

Theo

On Thu July 22 2010 11:36 pm, ash25 wrote:

## > > Yes it is possible to write a swap program using just two variables, but > this is true only for integral numbers and plain character variables, > and not for complex types like strings, structures or classes… > > This code should do: > > Code: > -------------------- > a = a + b; > b = a - b; > a = a - b; > -------------------- > > > Why it ain’t true for floating point numbers is binary operations on > two floating point numbers are not associative (there might be some > round-off errors)… > > This also fails if a+b or a-b either underflows or overflows the register.

P. V.
“We’re all in this together, I’m pulling for you.” Red Green

Yep, you’re right. The XOR method is reliable (and may be faster on some processors as well) since it directly does bit manipulations instead of any arithmetic operations… And it can work for floating point numbers as well after doing a typecast in this manner…

``````  float a = -3.5;
float b = 4.5;
*((unsigned int*)(&a)) = *((unsigned int*)(&a)) ^ *((unsigned int*)(&b));
*((unsigned int*)(&b)) = *((unsigned int*)(&a)) ^ *((unsigned int*)(&b));
*((unsigned int*)(&a)) = *((unsigned int*)(&a)) ^ *((unsigned int*)(&b));
printf("a = %f b = %f
", a, b);
``````