c# using bitwise XOR for swapping

前端 未结 7 1531
借酒劲吻你
借酒劲吻你 2020-12-18 12:40
void swap(ref int x, ref int y)
{       x = x ^ y;   y = y ^ x;   x = x ^ y;  }

im learning about bitwise XOR. how is this swapping occurring? it\'

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 13:14

    Beware. This method has a very very nasty property. It was used in one of the Underhanded C Contest entries. It will work happily... until one day someone tries something like swapping two array elements a[i] and a[j] without assuring that i!=j.

    When both references refer to the same variable, this method zeroes it.

提交回复
热议问题