加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用XOR交换值

发布时间:2020-12-16 09:49:44 所属栏目:百科 来源:网络整理
导读:参见英文答案 Sequence Point – Xor Swap on Array get wrong result????????????????????????????????????1个 ???????????? How does XOR variable swapping work?????????????????????????????????????9个 这两个宏有什么区别? #define swap(a,b) (((a)
参见英文答案 > Sequence Point – Xor Swap on Array get wrong result????????????????????????????????????1个
>???????????? How does XOR variable swapping work?????????????????????????????????????9个
这两个宏有什么区别?

#define swap(a,b)    (((a) ^ (b)) && ((a) ^= (b) ^= (a) ^= (b)))

要么

#define swap(a,b)    (((a) ^ (b)) && ((b) ^= (a) ^= (b),(a) ^= (b)))

我看到第二个宏here,但无法理解为什么它不像第一个那样写?我错过了一个特殊原因吗?

解决方法

首先将在C99??和C11中调用未定义的行为.

在C99中,可以理解为;由于缺少序列点,它们将调用未定义的行为.

C-faq:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore,the prior value shall be accessed only to determine the value to be stored.

说明:
第一个是在两个序列点之间修改两次,因此根据语句未定义行为:在前一个和下一个序列点之间,对象的存储值最多只能通过表达式的计算修改一次.就是这样(不需要考虑b).

C11文档说:

6.5表达式(第2页):

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object,the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression,the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.84)

在(a)^ =(b)^ =(a)^ =(b)中,对a的副作用是未序列的,因此调用未定义的行为.应该指出的是,C11 6.5 p1表示:

[…] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator.

这保证了

(a) ^= (b) ^= (a) ^= (b)  
 |      |      |      | 
 1      2      3      4

保证在最左边^ =运算符的结果计算之前计算所有子表达式1,2,3和4.但是,这并不能保证在最左侧^ =运算符的结果的值计算之前保证表达式3的副作用.

1.重点是我的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读