C语言 宏定义 swap

2018-08-22  本文已影响0人  guanjianhe

方法1:

#define swap(x,y)   do{x=x+y;y=x-y;x=x-y;}while(0)

方法2:

#define swap(x,y)   do{a^=b;b^=a;a^=b;}while(0)

说明:

  1. a^=b;:把a^b结果赋值给a
  2. b^=a;:相当于b=b^(a^b)。而b^(a^b)等于a^b^bb^b的结果为0因为同一个数与本身相异或,结果必为0因此b的值等于a^0,即a
  3. a^=b;:由于a的值等于a^bb的值等于a,因此,相当于a=(a^b)^a,即a的值等于b^a^a,相当于b^0,等于b

注:此方法只适用于整型数据

方法3:

#define swap(x,y)   do{typeof(x) t;t=x;x=y;y=t;}while(0)
#include <stdio.h>

#define swap1(x,y)   do{x=x+y;y=x-y;x=x-y;}while(0)
#define swap2(x,y)   do{a^=b;b^=a;a^=b;}while(0)
#define swap3(x,y)   do{typeof(x) t;t=x;x=y;y=t;}while(0)

int main()
{
    int a=2,b=3;
    float fa=2.5f,fb=4.2f;
    
    printf("交换前a=%d\t,b=%d\n",a,b);
    swap1(a,b);
    printf("交换后a=%d\t,b=%d\n\n",a,b);
    
    printf("交换前a=%d\t,b=%d\n",a,b);
    swap2(a,b);
    printf("交换后a=%d\t,b=%d\n\n",a,b);
    
    printf("交换前a=%d\t,b=%d\n",a,b);
    swap3(a,b);
    printf("交换后a=%d\t,b=%d\n\n",a,b);
    
    
    
    printf("交换前fa=%.2f\t,fb=%.2f\n",fa,fb);
    swap1(fa,fb);
    printf("交换后fa=%.2f\t,fb=%.2f\n\n",fa,fb);
    
    printf("交换前fa=%.2f\t,fb=%.2f\n",fa,fb);
    swap2(fa,fb);
    printf("交换后fa=%.2f\t,fb=%.2f\n\n",fa,fb);
    
    printf("交换前fa=%.2f\t,fb=%.2f\n",fa,fb);
    swap3(fa,fb);
    printf("交换后fa=%.2f\t,fb=%.2f\n\n",fa,fb);   
   
   return 0;
}
输出:
交换前a=2  ,b=3
交换后a=3  ,b=2

交换前a=3  ,b=2
交换后a=2  ,b=3

交换前a=2  ,b=3
交换后a=3  ,b=2

交换前fa=2.50  ,fb=4.20
交换后fa=4.20  ,fb=2.50

交换前fa=4.20  ,fb=2.50
交换后fa=4.20  ,fb=2.50

交换前fa=4.20  ,fb=2.50
交换后fa=2.50  ,fb=4.20
上一篇下一篇

猜你喜欢

热点阅读