CppCheck 警告:表达式取决于 x = x |= (1 << 3) 中的求值顺序

CppCheck warning: expression depends on order of evaluation in x = x |= (1 << 3)

C中的代码行是

x = x |= (1 << 3);

这给出了一个 cppCheck 错误:"Expression 'x=x|=1' depends on order of evaluation of side effects"

而行

x |= (1 << 3);

还可以。

我以为

x = x |= (1 << 3);

相同
x = x = x | (1 << 3);

这只是

x = (x = (x | (1 << 3)));

实际上对 x 的外部赋值无效,这意味着结果与

相同
x |= (1 << 3);

那么 CppCheck 到底在抱怨什么?

编辑:认为它重复了为什么 j = j++j++ 相同或不同,这在上面提到的问题中已经讨论过。

@Cornstalks 的这句话link on sequence points 解释得很好。

Expressions ... which modify the same value twice are abominations which needn't be allowed (or in any case, needn't be well-defined, i.e. we don't have to figure out a way to say what they do, and compilers don't have to support them).

C 标准对这些类型的表达式没有任何强制要求,因此没有在所有环境中保证的特定计算顺序。

一个相当快速&&简单的解释:

x = x |= 1 在副作用(对 x 的修改)方面几乎等同于 x = x += 1x = x += 1 等同于 C 中的 x = ++x。这个表达式是 well-known undefined expression.

了解更多信息 [here]