gpt4 book ai didi

c++ - 在单行中通过 XOR 交换整数。在 C++11 中真的允许吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:04 25 4
gpt4 key购买 nike

我仍然无法清楚地理解表达式 x ^= y ^= x ^= y;在 C++11 中有效(正如他们在 thread 中所说)还是会导致未定义的行为?

链接给出的理由似乎很有说服力,但 clang 抛出一个 warning :

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

此外,如果两个版本:

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

被认为是等效的(并且在 C++11 中定义明确),为什么它会给出不同的结果(firstsecond)?

此外,应该注意 gcc 给出了一个 warning仅在第二版代码上关于序列点。

最佳答案

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 = x ... 中只计算一次。不幸的是,对于 xor,操作数的评估是无序的。 IE。

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

适用。但是现在我们遇到了一个问题:

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

值(value)计算(这隐含在对最左边的两个 xx 的单数求值中)和副作用彼此无序,因此我们推导出 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.

关于c++ - 在单行中通过 XOR 交换整数。在 C++11 中真的允许吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29315133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com