When I first started working a mainframe assembler programmer showed me how they swap to values without using the traditional algorithm of:a = 0xBABEb = 0xFADEtemp = aa = bb = tempWhat they used to swap two values - from a bit to a large buffer - was:a = 0xBABEb = 0xFADEa = a XOR bb = b XOR aa = a XOR bnowb == 0xBABEa == 0xFADEwhich 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.
Is this XOR value swap algorithm still in use or useful
algorithms
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 being xor'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 a XCHG 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.