The exchange method of two variables in C language
1. The method of establishing temporary variables
#include <stdio.h>
int main(){
int a=5;
int b=3;
int c=0;
printf("a=%d,b=%d\n",a,b);
c=a;
a=b;
b=c;
printf("a=%d,b=%d\n",a,b);
return 0;
}
2. The method of not creating temporary variables
2.1 But this method has an overflow problem
#include <stdio.h>
int main(){
int a=5;
int b=3;
printf("a=%d,b=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("a=%d,b=%d\n",a,b);
return 0;
}
2.2 Use the XOR method, but the method is not easy to understand
#include <stdio.h>
int main(){
int a=5;
int b=3;
printf("a=%d,b=%d\n",a,b);
a=a^b;
b=a^b;
a=a^b;
printf("a=%d,b=%d\n",a,b);
return 0;
}
operation result