通过XOR在单行中交换整数。是否真的允许在c ++ 11? [英] Swap integers via XOR in single line. Is it really allowed in c++11?

查看:158
本文介绍了通过XOR在单行中交换整数。是否真的允许在c ++ 11?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是不清楚是否在C ++ 11中有效的表达式 x ^ = y ^ = x ^ = y;
在此线程),否则会导致未定义的行为?

I still could not clearly understand whether the expression x ^= y ^= x ^= y; valid in C++11 (as they say in this thread) or it leads to undefined behavior?

链接给出的原因似乎令人信服,但clang引发了一个警告

The reasons given by the link seem convincing, but clang throws a warning:


警告:无法修改并访问'x'[-Wunsequenced]

warning: unsequenced modification and access to 'x' [-Wunsequenced]

此外,如果两个版本:

x ^= y ^= x ^= y; // (1) 
x = x ^ (y = y ^ (x = (x ^ y))); // (2)

被认为是等效的(并且在C ++ 11中定义良好)给出不同的结果(第一第二个)?

considered equivalent (and well-defined in C++11), why it gives different results (first, second)?

此外,应该注意,gcc给出了

Additionally, it should be noted that the gcc gives a warning about sequence point only on the second version of code.

推荐答案

关于序列点的讨论,请参阅下面的例子:crooked.com/a/ff6bb101c3b55ff4\">

赋值运算符(=)和复合赋值运算符全部由
组从右到左。 [..]

形式 E1 op = E2 的表达式的行为相当于 E1 = E1 op E2 ,除了 E1
只评估一次。

The assignment operator (=) and the compound assignment operators all group right-to-left. [..]
The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.

因此,您的代码等同于

x = x ^ (y ^= (x ^= y)));

...在 x = x ...中只评估一次
不幸的是,对于xor的,对操作数的评估是无效的。也就是说

... with x evaluated only once in x = x .... Unfortunately, for xor's, the evaluation of the operands is unsequenced. I.e.


除非另有说明,否则对个别运算符
的操作数和各个表达式的子表达式的计算结果无效。

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

适用。但现在我们有一个问题:

applies. But now we have a problem:

   x = x ^ (y ^= (x ^= y)));
//     *          ******
//     |            |
//     |            Side effect
//     Value computation

价值计算 x 对于最左边的两个 x )和副作用不相互排序,因此我们诱导UB: / p>

The value computation (which is implied in the singular evaluation of x for the two leftmost x) and the side effect are unsequenced wrt each other, hence we induce UB:


如果对标量对象的副作用不是相对于
的顺序,对同一标量对象的另一个副作用或值计算
使用相同标量对象的值,行为是未定义的。

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

这篇关于通过XOR在单行中交换整数。是否真的允许在c ++ 11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆