c++ 无第三变量交换问题
#include <iostream>
using namespace std;
void Swap1(int& a, int& b)
{
a += b;
b = a - b;
a -= b;
}
void Swap2(int& a, int& b)
{
a *= b;
b = a / b;
a /= b;
}
void Swap3(int& a, int& b)
{
a ^= b;
b ^= a;
a ^= b;
}
void Swap4(int& a, int&b)
{
a = b + (b = a) * 0;
}
int main(int argc, char* argv[])
{
int a = 3, b = 5;
cout << a << " " << b << endl;
Swap1(a, b);
cout << a << " " << b << endl;
Swap2(a, b);
cout << a << " " << b << endl;
Swap3(a, b);
cout << a << " " << b << endl;
Swap4(a, b);
cout << a << " " << b << endl;
system("pause");
}
结果:
注意最后一种做法是错误的。