Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› To Swap Between 2 Variable Without Using Third Variable

To Swap Between 2 Variable Without Using Third Variable

C Programming Tricks

To swap between 2 variable without using third variable:

Use this code to swap values between variable a and variable b. This method is much faster than using 3rd variable. assuming that a and b is integer.

 a^=b;
 b^=a;
 a^=b;
 

And to add more fun, A and B variables can be in any format, from pointer to long floating point format. It uses XOR method to XORed the bits. Try it for yourself if you are not sure what I'm talking about.

Partners