Weird XOR swap behavior while zeroing out data

前端 未结 3 1949
感情败类
感情败类 2021-01-21 07:31

Thanks Doug. Here\'s the fix:

void swap(int& a, int& b) {
    if (&a == &b) // added this check to ensure the same address is not passed in
              


        
相关标签:
3条回答
  • 2021-01-21 08:21

    Anything xor'd with itself is zero.

    0 讨论(0)
  • 2021-01-21 08:22

    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
    
    0 讨论(0)
  • 2021-01-21 08:26

    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.

    0 讨论(0)
提交回复
热议问题