DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Swap Values Without Temporary Variable

09.23.2006
| 9196 views |
  • submit to reddit
        The XOR swap algorithm is an inefficient method of swapping two variables. http://en.wikipedia.org/wiki/Xor_swap_algorithm

void XORSwap(void *x, void *y)
{
   *x ^= *y;
   *y ^= *x;
   *x ^= *y;
}
    

Comments

Snippets Manager replied on Tue, 2007/01/09 - 10:34pm

You might mention that the code snippet doesn't actually work (you can't XOR two pointers, even void pointers), but it illustrates the technique. It is not necessarily inefficient. On Intel under GCC, the compiler actually knows about this trick and produces a single XCHG instruction if possible! Very cool. Anyway, I like this trick.