C++利用宏实现变量交换的三种方式

 

#include <iostream>

using namespace std;

//引入中间变量
#define SWAP1(a,b) {int tmp=a;a=b;b=tmp;} 

//算数技巧,需要考虑越界与否
#define SWAP2(a,b) {a=a+b;b=a-b;a=a-b;}

//位运算,不考虑越界
#define SWAP3(a,b) {a=a^b;b=a^b;a=a^b;}

int main()
{
    int a = 1,b = 2;
    SWAP1(a,b);
    cout << "引入中间变量:" << a << " " << b << endl;

    SWAP2(a,b);
    cout << "算数技巧:" << a << " " << b << endl;

    SWAP3(a,b);
    cout << "位运算:" << a << " " << b << endl;

    return 0;
}

 

 

作者:耑新新,发布于  博客园

转载请注明出处,欢迎邮件交流:zhuanxinxin@aliyun.com

posted on 2019-08-31 22:04  Arthurian  阅读(794)  评论(0编辑  收藏  举报