When I first started working a mainframe assembler programmer showed me how they swap to values without using the traditional algorithm of:
a = 0xBABE
b = 0xFADE
temp = a
a = b
b = temp
What they used to swap two values – from a bit to a large buffer – was:
a = 0xBABE
b = 0xFADE
a = a XOR b
b = b XOR a
a = a XOR b
now
b == 0xBABE
a == 0xFADE
which swapped the contents of 2 objects without the need for a third temp holding space.
My question is: Is this XOR swap algorithm still in use and where is it still applicable.
Best Answer
When using
xorswap
there's a danger of supplying same variable as both arguments to the function which zeroes out the said variable due to it beingxor
'd with itself which turns all the bits to zero. Of course this itself would result in unwanted behavior regardless of algorithm used, but the behavior might be surprising and not obvious at first glance.Traditionally
xorswap
has been used for low-level implementations for swapping data between registers. In practice there are better alternatives for swapping variables in registers. For example Intel's x86 has aXCHG
instruction which swaps the contents of two registers. Many times a compiler will figure out the semantics of a such function (it swaps contents of the values passed to it) and can make its own optimizations if needed, so trying to optimize something as trivial as a swap function does not really buy you anything in practice. It's best to use the obvious method unless there's a proven reason why it would be inferior to say xorswap within the problem domain.