假設有兩個int型變量x和y,爲了交換二者數值,我們可以藉助臨時變量,如下所示:
int tmp = x;
x = y;
y = tmp;
利用異或操作的特性,不使用臨時變量也可以到達交換的目的,如下所示:
x = x ^ y;
y = x ^ y; //即 y = (x ^ y) ^ y = x,y的值現在已經成x原來的值了
x = x ^ y; //x的值現在已經成y原來的值了
下面程序實現數組的反轉功能,即如果數組原來爲 1 、2、3、 4 、5 ,
反轉後則成爲5、4、3、2、1。
下面的程序能否正確實現該功能:
#include <stdio.h>
void inplace_swap(int *x, int *y)
{
*y = *x ^ *y; /* Step 1 */
*x = *x ^ *y; /* Step 2 */
*y = *x ^ *y; /* Step 3 */
}
void reverse_array(int a[], int cnt)
{
int first, last;
for (first = 0, last = cnt-1;first <= last;first++,last--)
inplace_swap(&a[first], &a[last]);
}
int main(void)
{
int a[5] = {1,2,3,4,5};
int i = 0;
reverse_array(a,5);
for(; i <5; i++)
printf("%d\t", a[i]);
printf("\n");
return 0;
}
輸出結果不是5、4、3、2、1,而是5 、4、0、2、1。Why?
問題出在inplace_swap(&a[2], &a[2]),該函數執行Step 1後, a[2]的數值被改寫成了0,
即此時*x = *y = 0了。