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:
“... 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?)
“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 (18441900)