Search code examples
cswapxor

Could XOR-swap cause an overflow and does it work with floats?


Let's say I want to swap variables a and b using XOR-swap.

a = a ^ b;
b = a ^ b;
a = a ^ b;

Could this cause an overflow, and can I swap those numbers when they are of type float or double?


Solution

  • This will have undefined behaviour; it could cause any number of problems.

    Even assuming you found a reliable way to get the bit representation of the floating point number as an integer of the same size, you might still manage to create a floating point trap representation when you do the intermediate XOR, so storing that into the floating point value could be problematic.

    The XOR hack is passé. Use a temporary. Your computer probably has a lot of floating point registers, and using them is really fast.