How to swap two numbers without using a temporary variable?

Given two variables, x and y, swap two variables without using a third variable.

Method 1 (Using Arithmetic Operators)
The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.

#include <stdio.h>
int main()
{
  int x = 10, y = 5;

  // Code to swap 'x' and 'y'
  x = x + y;  // x now becomes 15
  y = x - y;  // y becomes 10
  x = x - y;  // x becomes 5

  printf("After Swapping: x = %d, y = %d", x, y);

  return 0;
}

Output:

After Swapping: x = 5, y = 10

Multiplication and division can also be used for swapping.

#include <stdio.h>
int main()
{
  int x = 10, y = 5;

  // Code to swap 'x' and 'y'
  x = x * y;  // x now becomes 50
  y = x / y;  // y becomes 10
  x = x / y;  // x becomes 5

  printf("After Swapping: x = %d, y = %d", x, y);

  return 0;
}

Output:

After Swapping: x = 5, y = 10

Method 2 (Using Bitwise XOR)
The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010).

#include <stdio.h>
int main()
{
  int x = 10, y = 5;

  // Code to swap 'x' (1010) and 'y' (0101)
  x = x ^ y;  // x now becomes 15 (1111)
  y = x ^ y;  // y becomes 10 (1010)
  x = x ^ y;  // x becomes 5 (0101)

  printf("After Swapping: x = %d, y = %d", x, y);

  return 0;
}

Output:

After Swapping: x = 5, y = 10

Problems with above methods
1) The multiplication and division based approach doesn’ work if one of the numbers is 0 as the product becomes 0 irrespective of the other number.

2) Both Arithmetic solutions may cause arithmetic overflow. If x and y are too large, addition and multiplication may go out of integer range.

3) When we use pointers to variable and make a function swap, all of the above methods fail when both pointers point to the same variable. Let’s take a look what will happen in this case if both are pointing to the same variable.

// Bitwise XOR based method
x = x ^ x; // x becomes 0
x = x ^ x; // x remains 0
x = x ^ x; // x remains 0

// Arithmetic based method
x = x + x; // x becomes 2x
x = x – x; // x becomes 0
x = x – x; // x remains 0

Let us see the following program.

#include <stdio.h>
void swap(int *xp, int *yp)
{
    *xp = *xp ^ *yp;
    *yp = *xp ^ *yp;
    *xp = *xp ^ *yp;
}

int main()
{
  int x = 10;
  swap(&x, &x);
  printf("After swap(&x, &x): x = %d", x);
  return 0;
}

Output:

After swap(&x, &x): x = 0

Swapping a variable with itself may needed in many standard algorithms. For example see this implementation of QuickSort where we may swap a variable with itself. The above problem can be avoided by putting a condition before the swapping.

#include <stdio.h>
void swap(int *xp, int *yp)
{
    if (xp == yp) // Check if the two addresses are same
      return;
    *xp = *xp + *yp;
    *yp = *xp - *yp;
    *xp = *xp - *yp;
}
int main()
{
  int x = 10;
  swap(&x, &x);
  printf("After swap(&x, &x): x = %d", x);
  return 0;
}

Output:

After swap(&x, &x): x = 10

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above









Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.

  • Chita Ranjan Satapathy

    One line code can make the swap. How ever there are possibilities like value overflow during arithmetic operation.
    Anyway I am just writing the method.
    a = 5;
    b = 10;

    a = (a*b)/(b=a);

    Now a = 10 and b=5.

  • kri

    // Arithmetic based method

    x = x + x; // x becomes 2x

    x = x – x; // x becomes x

    x = x – x; // x becomes 0

    the result of the second assignment should be zero, not x

  • Blancos

    always use temp variable when swapping. no need for tricks which lead to unexpected outcomes.

  • coder027

    good discussion..thanks geeksforgeeks

  • We The Computer Guys
  • Guest

    int a = 0;
    int b = 20;
    cout<<"nA : "<<a<<" , B : "<<b;

    a = a ^ b;

    b = a ^ b;

    a = a ^ b;

    cout<<"nA : "<<a<<" , B : "<<b;

    Output:

    A : 0 , B : 20
    A : 20 , B : 0

  • Swapping two numbers —> http://opensourceforgeeks.blogspot.in/2013/12/swapping-two-numbers-without-using.html and
    Swapping two Strings —> http://opensourceforgeeks.blogspot.in/2013/12/swapping-two-strings-without-using.html
    without using temporary variables. Java Code with example.

  • xxmajia

    Thanks for sharing.
    But I Agree with @Qianqian

    If we look at the problem at the CPU instructions perspective, use tmp will be better than all above 3 method, i have run a benchmark agains all those 4 method (including the 4th by using temp variable). without surprise, the 4th way beats all above 3 method. And the reason is how CPU move the variable into register and how many register we need to use.

    So this 3 can be used in an interview for “show off”, but just make sure, we do know how it actually works

  • Gaurav Jain

    a^=b^=a^=b;

  • DIDI

    Python:
    a, b = b, a

  • Qianqian

    But, what’s the advantage of this method compared to the temporary variable method? speed or others?
    In my opinion, IF will introduce a jump in the CPU streamline which is not good for speed.

  • Harsha

    a=a+b-(b=a).

    • Amit Jain

      I think,this behavior is dependent on compiler. If compiler performs b=a before using value of b in a+b,the output will be a=a,b=a. In other case,we get the value swapped,when b is used first in a+b.

  • Amit Jain

    Instead of

    if (xp == yp) // Check if the two addresses are same
    return;
    It could have been better::
    if (*xp == *yp) // Check if the two values are same
    return;
    because no need to swap if two values are same

    • Kartik

      Amit, thanks for sharing your thoughts. This may not work if xp and yp are pointers to structures. Please correct me if i am wrong.

      • Siva Krishna

        “This may not work if xp and yp are pointers to structures” can you elaborate?

        • Kartik

          A situation where we have two “struct ABC” type variables and we want to swap them. The prototype of swap would be swap(struct ABC *a, struct ABC *b).

          We cannot compare two struct variables using ==. For example if (*a == *b) is invalid.

          • Amit Jain

            What I feel is that if we want to swap 2 structures then we can’t use addition or multiplication or xor directly. At end, we must swap each element individually. So then checking values will be better. Please correct me if I missed something.

          • pavan

            it can be done in 5 ways see in …

            http://www.programmerschat.blogspot.com

          • vishal

            For structures , we can use memcmp
            memcmp( &str1, %str2, sizeof(str1)
            );

  • Kailash

    good, you rock