交换两变量值

下面两种方法不使用第三变量实现了两变量值的交换,C代码如下:

 1 #include <stdio.h>
 2 
 3 #define SWAP1(a,b) {a=a+b; b=a-b; a=a-b;}
 4 
 5 #define SWAP2(a,b) {a^=b; b^=a; a^=b;}
 6 
 7 
 8 int main(void)
 9 {
10     int a=1234, b=5678;
11     
12     printf("a=%d, b=%d
", a, b);
13     printf("DO SWAP1:
");
14     SWAP1(a,b);
15     printf("a=%d, b=%d
", a, b);
16     
17     printf("DO SWAP2:
");
18     SWAP2(a,b);
19     printf("a=%d, b=%d
", a, b);
20 
21     system("pause");
22     return 0;
23 }

编译后运行,结果如下:

a=1234, b=5678
DO SWAP1:
a=5678, b=1234
DO SWAP2:
a=1234, b=5678
请按任意键继续. . .

原文地址:https://www.cnblogs.com/geekham/p/4240548.html