XOR Swap Algorithm - Code Example

Code Example

A C function that implements the XOR swap algorithm:

void xorSwap (int *x, int *y) { if (x != y) { *x ^= *y; *y ^= *x; *x ^= *y; } }

Note that the code does not swap the integers passed immediately, but first checks if their addresses are distinct. This is because, if the addresses are equal, the algorithm will fold to a triple *x ^= *x resulting in zero.

The body of this function is sometimes seen incorrectly shortened to if (x != y) *x^=*y^=*x^=*y;. This code has undefined behavior, since it modifies the lvalue *x twice without an intervening sequence point.

Read more about this topic:  XOR Swap Algorithm

Famous quotes containing the word code:

    Acknowledge your will and speak to us all, “This alone is what I will to be!” Hang your own penal code up above you: we want to be its enforcers!
    Friedrich Nietzsche (1844–1900)

    Faultless honesty is a sine qua non of business life. Not alone the honesty according to the moral code and the Bible. When I speak of honesty I refer to the small, hidden, evasive meannesses of our natures. I speak of the honesty of ourselves to ourselves.
    Alice Foote MacDougall (1867–1945)