How to swap the content of two variables without using an intermediate storage location?
Traditionally most programmers use an extra variable when it’s come to swap the content of two variable. well, some programmers believe that there are no other ways to swap two variables with out using another temporary variable. The professor who taught me programming when I was in first year college said “You have two cups, one filled with water and the other filled with cola. Can you swap the content of them without using an extra cup?!!”
The tradition way looks like:
int a=10,b=35; int temp; temp = a; a = b; b = temp;
Now with out using the temp variable:
int a=10,b=35; a = a + b; //a = 10+35 = 45 b = a - b; //b = 45-35 = 10 a = a - b; //a = 45-10 = 35
Very simple, isn’t it?
but it doesn’t work with the water and cola example
You must first make sure that the sum a+b in line 2 doesn’t exceed the int limit
Another way is to use XOR but this one doesn’t work with floats (only integers)
int a=10; //a = 001010 int b=35; //b = 100011 a ^= b; // a = 001010 ^ 100011 = 101001 b ^= a; // b = 100011 ^ 101001 = 001010 a ^= b; // a = 101001 ^ 001010 = 100011
great, and simple
simple thanks…..
why no floats??
because floats have some special representation in binary
I didn’t test it, it may work fine or it may need a simple trick to get it work with floats.
feel free to take the code edit it and I’ll be happy if you share the result here.
When I explain variable swapping, I always use the water and cola example too ^_^
As for XOR’ing, casting the floats to integers should make it work just fine