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
本文来自博客园,作者:Arthurian,转载请注明原文链接:https://www.cnblogs.com/Arthurian/p/9553844.html
欢迎邮件交流:zhuanxinxin@aliyun.com