#include <stdio.h>
void swap1(int *a, int *b); void swap2(int *a, int *b); void swap3(int *a, int *b);
int main() { int a = 2; int b = 6;
printf("Before swap, a = %d, b = %d\n", a, b);
swap1(&a, &b); printf("First swap, a = %d, b = %d\n", a, b); swap2(&a, &b); printf("Second swap, a = %d, b = %d\n", a, b); swap3(&a, &b); printf("Third swap, a = %d, b = %d\n", a, b); return 0; }
void swap1(int *a, int *b) { *a = *a ^ *b; *b = *a ^ *b; //*b = *a ^ *b = (*a ^ *b) ^*b = *a ^ (*b ^ *b) = *a ^ 0 = *a;
*a = *a ^ *b; //*a = *a ^ *b = (*a ^ *b) ^*a = (*a ^ *a) ^*b = 0 ^ *b = *b;
}
void swap2(int *a, int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; }
void swap3(int *a, int *b) { *a = *a + *b - (*b = *a); //*b=*a是一个复试表达式,它除了将*a赋给*b外,它本身可以当作一个数,这个数的值就是*a.
}
|