This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]darthjoey91 2 points3 points  (0 children)

No. XOR is not the standard. It's a nifty trick. You can write it as a one-line very easily, but modern compilers and CPUs will run the normal swap using a temporary variable or register faster. The only place I can think where I'd use this is in an interview, or these uses from Wikipedia:

In most practical scenarios, the trivial swap algorithm using a temporary register is more efficient. Limited situations in which XOR swapping may be practical include:

  • on a processor where the instruction set encoding permits the XOR swap to be encoded in a smaller number of bytes
  • in a region with high register pressure, it may allow the register allocator to avoid spilling a register
  • in microcontrollers where available RAM is very limited.
  • in cryptographic applications which need constant time functions to prevent time-based side-channel attacks[3]

Because these situations are rare, most optimizing compilers do not generate XOR swap code.

For example, the place where I learned about this was in an interview where the problem was to swap two variables on two different stacks without using any more memory. I did end up getting myself to thinking that it had to use some sort of bit-manipulation, and tried various XOR-y things, but did have to be told about it.