交换变量值的5种方法

#include <stdio.h>

#define swap_macro_0(a, b)
do {
typeof(a) c;
c = a;
a = b;
b = c;
} while(0)

#define swap_macro_1(a, b)
do {
a = a + b;
b = a - b;
a = a - b;
}while(0)

#define swap_macro_2(a, b)
do {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}while(0)

#define swap_macro_3(a, b)
do {
a = a * b;
b = a / b;
a = a / b;
}while(0);

#define swap_macro_4(a, b)
do {
a = a + b - (b = a);
}while(0);

int main()
{
int type, a, b;

scanf("%d, %d, %d", &type, &a, &b);
printf("before a = %d, b = %d ", a, b);
switch(type)
{
case 0:
{
swap_macro_0(a, b);
break;
}
case 1:
{
swap_macro_1(a, b);
break;
}
case 2:
{
swap_macro_2(a, b);
break;
}
case 3:
{
swap_macro_3(a, b);
break;
}
case 4:
{
swap_macro_4(a, b);
break;
}
default:
{
printf("unknown swap type! ");
return 0;
}
}
printf("after a = %d, b = %d ", a, b);
return 0;
}

原文地址:https://www.cnblogs.com/Leo_wl/p/3220790.html