Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The thing about the “Use XOR to swap two variables” trick is that it’s a version of this solution which works for any two real numbers (or integers):

  a = a - b
  b = a + b
  a = b - a
XOR is simply addition or subtraction modulo 2 for each bit, so making the above XOR looks like this:

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


The article touches on this, since its an important realization. In C, however, if the integers are not unsigned, the add/sub version exhibits UB on overflow, because C unnecessarily ties signed/unsignedness with overflow behavior (UB, two's complement, etc.).

Not that this is important, but could hint why this trick is more often shown with XOR than with add/sub.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: