其他分享
首页 > 其他分享> > c – 按位运算符可以有未定义的行为吗?

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

作者:互联网

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

例如,〜运算符在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)允许实现定义和未定义的方面.

标签:c-3,ones-complement,c,language-lawyer,bitwise-operators
来源: https://codeday.me/bug/20191001/1838765.html