tbwshc

tbw

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  95 Posts :: 8 Stories :: 3 Comments :: 0 Trackbacks

常用链接

留言簿(4)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

(转载)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.

posted on 2012-08-12 12:46 tbwshc 阅读(171) 评论(0)  编辑 收藏 引用