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:
“Motion or change, and identity or rest, are the first and second secrets of nature: Motion and Rest. The whole code of her laws may be written on the thumbnail, or the signet of a ring.”
—Ralph Waldo Emerson (18031882)
“Hollywood keeps before its child audiences a string of glorified young heroes, everyone of whom is an unhesitating and violent Anarchist. His one answer to everything that annoys him or disparages his country or his parents or his young lady or his personal code of manly conduct is to give the offender a sock in the jaw.... My observation leads me to believe that it is not the virtuous people who are good at socking jaws.”
—George Bernard Shaw (18561950)