Jump to content

Xor swap algorithm/C code

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 140.254.26.226 (talk) at 19:07, 27 June 2003 ( Implementation of XOR swap in C.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

C Code to implement XOR swap of x and y:

x ^= y; y ^= x; x ^= y;

If you want to use this a lot, it is probably best set up as a compiler macro:

  1. define xorSwap(x,y) {x=x^y; y=x^y; x=x^y;}

The function declaration would look like:

void xorSwap(int * x, int * y) {

 *x = *x ^ *y;
 *y = *x ^ *y;
 *x = *x ^ *y;

}

See: Xor swap algorithm