按位运算符可以有未定义的行为吗?

Can bitwise operators have undefined behavior?

按位运算符(~&|^)对其提升的操作数的按位表示进行运算。这样的操作会导致未定义的行为吗?

例如,~运算符在C标准中是这样定义的:

6.5.3.3 Unary arithmetic operators

The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

在所有体系结构上,~0 生成一个位模式,其中符号位设置为 1,所有值位设置为 1。在一个补码体系结构中,此表示对应于负零。这个位模式可以是陷阱表示吗?

对于更常见的架构,是否还有涉及简单按位运算符的未定义行为的其他示例?

对于补码系统,在有符号整数中明确列出了不支持负零的补码系统的可能性( C11 6.2.6.2p4):

If the implementation does not support negative zeros, the behavior of the &, |, ^, ~, <<, and >> operators with operands that would produce such a value is undefined.

话又说回来,一个人的补体系统并不完全常见;例如 GCC 不支持任何!

C11 确实暗示 实现定义和未定义的方面 只允许 signed types (C11 6.5p4)。