MACRO
OMNI_XOR_SWAP - A helper macro defining an XOR swap
DESCRIPTION top
Swap two objects via an XOR swap, defined as such:
Can be used as such:
The output would be:
Swap two objects via an XOR swap, defined as such:
#define OMNI_XOR_SWAP(a, b) a ^= b; b ^= a; a ^= b
int x = 10; int y = 255; std::cout << x << "," << y << std::endl; OMNI_XOR_SWAP(x, y); std::cout << x << "," << y << std::endl;
10, 255 255, 10
NOTES top
An XOR swap might be efficient on memory since it does not utilize temporaries, but it might not be as fast in CPU time as one might initially expect, especially for different types or types that do not fall on a clean word boundary. Test your swaps in a tight loop to verify if an XOR swap is any faster than a std::swap or copy-swap.
An XOR swap might be efficient on memory since it does not utilize temporaries, but it might not be as fast in CPU time as one might initially expect, especially for different types or types that do not fall on a clean word boundary. Test your swaps in a tight loop to verify if an XOR swap is any faster than a std::swap or copy-swap.