方法一:
#include <stdio.h>
int main()
{
int a = 3;
int b = 5;
printf("交换前,a=%d,b=%d",a,b);
a = a + b;
b = a - b;
a = a - b;
printf("交换后,a=%d,b=%d",a,b);
return 0;
}
方法二:
#include <stdio.h>
int main()
{
int a = 3;
int b = 5;
printf("交换前,a=%d,b=%d",a,b);
a = a * b;
b = a / b;
a = a / b;
printf("交换后,a=%d,b=%d",a,b);
return 0;
}
以上的方法容易造成越界,尤其是方法二
方法三是一种不会造成越界的方法:
#include <stdio.h>
int main()
{
int a = 3;
int b = 5;
printf("交换前,a=%d,b=%d",a,b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("交换后,a=%d,b=%d",a,b);
return 0;
}
//00000000000000000000000000000011 - 3 - a
//00000000000000000000000000000101 - 5 - b
//11111111111111111111111111111001 - 3 ^ 5 a ^ b = a
//00000000000000000000000000000011 - 3 ^ 5 ^ 5 a ^ b = b
//00000000000000000000000000000101 - 3 ^ 5 ^ 3 ^ 5 ^ 5 a ^ b = a