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

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
aravind
Guest

yndi
Guest

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