Weird XOR swap behavior while zeroing out data

好久不见. 提交于 2019-12-01 20:15:34

Your swap a and b are the same location. The XOR hack only works when they are different locations.

I think in C; here's a table:

           &a != &b  &a == &b
           *a   *b   *a   *b
           -5   -5   -5   -5
*a ^= *b;   0   -5    0    0
*b ^= *a;   0   -5    0    0
*a ^= *b;  -5   -5    0    0

In addition to the existing answers, I'll just add that if you're going to do a test before swapping then you might as well change:

if (&a == &b) // added this check to ensure the same address is not passed in
    return;

to:

if (a == b) // check that values are different
    return;

This will handle the case where &a == &b and also the case where a == b, which may save some unnecessary swapping.

Anything xor'd with itself is zero.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!