gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:56:51 25 4
gpt4 key购买 nike

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

例如,~ 运算符在 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).

关于按位运算符可以有未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861035/

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