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:
“...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.”
—Ellen Glasgow (18731945)
“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)