按位运算符可以具有未定义的行为吗? [英] Can bitwise operators have undefined behavior?

查看:151
本文介绍了按位运算符可以具有未定义的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按位运算符(~&|^)对提升后的操作数的按位表示进行运算.这样的操作会导致不确定的行为吗?

Bitwise operators (~, &, | and ^) operate on the bitwise representation of their promoted operands. Can such operations cause undefined behavior?

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

For example, the ~ operator is defined this way in the C Standard:

6.5.3.3一元算术运算符

~运算符的结果是其(提升的)操作数的按位补码(即,当且仅当未设置转换后的操作数中的相应位时,结果的每个位才被设置).对操作数执行整数提升,并且结果具有提升的类型.如果提升的类型是无符号类型,则表达式~E等于该类型可表示的最大值减去E.

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.在一个人的补码体系结构中,此表示形式对应于负零.这个位模式可以作为陷阱表示吗?

On all architectures, ~0 produces a bit pattern with the sign bit set to 1 and all value bits set to 1. On a one's complement architecture, this representation correspond to a negative zero. Can this bit pattern be a trap representation?

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

Are there other examples of undefined behavior involving simple bitwise operators for more common architectures?

推荐答案

对于一个补码系统,明确列出了对于那些不支持负号负零的陷阱值的可能性.整数( C11 6.2.6.2p4 ):

For one's complement systems, there's explicitly listed the possibility of trap values for those that do not support negative zeros in signed integers (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不支持任何功能!

Then again, one's complement systems are not exactly common; as for example GCC doesn't support any!

C11确实暗示仅在

C11 does imply that the implementation-defined and undefined aspects are just allowed for signed types (C11 6.5p4).

这篇关于按位运算符可以具有未定义的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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