数据交换
加法交换
void arr_swap_addition(int *arr, int a, int b)
{
arr[a] = arr[a] + arr[b];
arr[b] = arr[a] - arr[b];
arr[a] = arr[a] - arr[b];
}
void swap_addition(int *a, int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
异或交换
void arr_swap_xor(int *arr, int a, int b)
{
arr[a] = arr[a] ^ arr[b];
arr[b] = arr[a] ^ arr[b];
arr[a] = arr[a] ^ arr[b];
}
void swap_xor(int *a, int *b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
验证
int main()
{
static int a[2] = {2, 1};
arr_swap_addition(a, 0, 1);
printf("arr_swap\r\n a[0] = %d a[1] = %d\r\n", a[0], a[1]);
arr_swap_xor(a, 0, 1);
printf("arr_swap_xor\r\n a[0] = %d a[1] = %d\r\n", a[0], a[1]);
swap_addition(&a[0], &a[1]);
printf("swap_addition\r\n a[0] = %d a[1] = %d\r\n", a[0], a[1]);
swap_xor(&a[0], &a[1]);
printf("swap_xor\r\n a[0] = %d a[1] = %d\r\n", a[0], a[1]);
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/95b64f205c324ff18743698843d59e2a.png)