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

  • submit to reddit
        The XOR swap algorithm is an inefficient method of swapping two variables.

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


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.