Swap two numbers without using third variable | 5 methods

Given two integers, swap them without using any third variable.



Method 1: (Using addition and subtraction operator)



Note that in pass by reference, a copy of the address of the actual parameter is passed and any changes made to these variables in the function will affect the original. This can also be achieved using pointers in C.



Method 2: (Using multiplication and division operator)



Method 3: (Using Bitwise XOR operator)



Method 4: (Using difference between two values)



Method 5: (Using single line expressions)

We can also use any of below expressions to swap two variables in single line.

  • x = x ^ y ^ (y = x);
  • x = x + y – (y = x);
  • x = (x * y) / (y = x);


1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

newest oldest most voted
Notify of


Method 5 is built upon a bunch of UBs, https://en.wikipedia.org/wiki/Sequence_point