(轉載)C++教程網www.cppcourse.com
第一種方法:
a = a + b;
b = a – b;
a = a – b;
第二種方法:
a=a^b;
b=a^b;
a=a^b;
或者
a^=b^=a^=b;
原理是:相同的兩數相異為0,任何數與0相異保留不變
但不推薦這么使用,c FAQs里有說明,用異或準確來講是undefined,Not portbably
Q: Here’s a slick expression:
a ^= b ^= a ^= b
It swaps a and b without using a temporary.
A: Not portably, it doesn’t. It attempts to modify the variable a twice between sequence points, so its behavior is undefined.
For example, it has been reported that when given the code
int a = 123, b = 7654;
a ^= b ^= a ^= b;
the SCO Optimizing C compiler (icc) sets b to 123 and a to 0.