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:

    Many people will say to working mothers, in effect, “I don’t think you can have it all.” The phrase for “have it all” is code for “have your cake and eat it too.” What these people really mean is that achievement in the workplace has always come at a price—usually a significant personal price; conversely, women who stayed home with their children were seen as having sacrificed a great deal of their own ambition for their families.
    Anne C. Weisberg (20th century)

    ... the self respect of individuals ought to make them demand of their leaders conformity with an agreed-upon code of ethics and moral conduct.
    Mary Barnett Gilson (1877–?)