Never been to DZone Snippets before?

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

swap values without temporary variable (See related posts)

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 on this post

bugsmasher posts on Jan 09, 2007 at 21:36
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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts