我尝试找到一个列出所有可能性的好答案(也许只有一种?)。
那么考虑有符号数和无符号数,哪些是在 C 语言中导致 UB 移位的方法?
最佳答案
C99 标准对按位移位运算符有这样的规定(添加了强调,^
用于表示求幂):
§6.5.7.3: The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
§6.5.7.4: The result ofE1 << E2
isE1
left-shiftedE2
bit positions; vacated bits are filled with zeros. IfE1
has an unsigned type, the value of the result isE1 × 2^E2
, reduced modulo one more than the maximum value representable in the result type. IfE1
has a signed type and non-negative value, andE1 × 2^E2
is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
**§6.5.7.5: The result ofE1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a non-negative value, the value of the result is the integral part of the quotient ofE1 / 2^E2
. IfE1
has a signed type and a negative value, the resulting value is implementation-defined.
因此,总而言之,如果满足以下任一条件,则行为未定义:
- 右操作数有符号且为负,或者
- 右操作数大于或等于左操作数的宽度(提升后),或者
- 左操作数有符号且为负,或者
- 执行左移并且左操作数有符号,结果值不能表示为有符号整数
关于c - 移位何时会导致未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617802/