How to swap the content of two variables without using an intermediate storage location?

Posted by on 20 Apr 2011. Filed under Programming Tips. You can follow any responses to this entry through the RSS 2.0. You can leave a response or trackback to this entry

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 :D

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
Share

5 Comments for “How to swap the content of two variables without using an intermediate storage location?”

  1. Mokhtar

    great, and simple

  2. manoj

    simple thanks…..

    • 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.

  3. Ahmed

    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 :)

Leave a Reply

Log in | Designed by Gabfire themes

[2checkout]