4 ms·
The xor swap can be dangerous: if variables have the same value, they xor to zero so you end up losing the values of both variables.
by diegocg 6y ago
The xor swap can be dangerous: if variables have the same value, they xor to zero so you end up losing the values of both variables.
- IgorPartola 6y agoSo you do a check beforehand for whether you need to swap them at all?
- flohofwoe 6y agoIt also works if both are equal since only one value will ever be zero: x=2, y=2: x^=y => x=0, y=2 y^=x => x=0, y=2 x^=y => x=2, y=2
- extropy 6y agoa = 5 b = 5 a = a ^ b = 0 b = a ^ b = 5 a = a ^ b = 5 You where saying?
- deleted 6y ago[deleted]
- tempodox 6y agoYou are wrong. Just try it out yourself. TFA actually explains why it still works even in that case.
- deleted 6y ago[deleted]
- tlb 6y agoNot if they have just the same value, but if they're the same memory location. So check the pointers: void swap(T &x, T &y) { if (&x == &y) return; x ^= y; y ^= x; x ^= y; }
- user-the-name 6y agoYou are confused about the problem here. It is not that both values are the same, it is you are applying the xor swap using pointers to values, and both pointers point to the same value in memory.
- deleted 6y ago[deleted]