c - 移位何时会导致未定义的行为

标签 c

我尝试找到一个列出所有可能性的好答案(也许只有一种?)。

那么考虑有符号数和无符号数,哪些是在 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 of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and non-negative value, and E1 × 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 of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1 / 2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

因此,总而言之,如果满足以下任一条件,则行为未定义:

  • 右操作数有符号且为负,或者
  • 右操作数大于或等于左操作数的宽度(提升后),或者
  • 左操作数有符号且为负,或者
  • 执行左移并且左操作数有符号,结果值不能表示为有符号整数

关于c - 移位何时会导致未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617802/

相关文章:

c - 检测到堆损坏 | C

c - 你知道为什么这个 C 代码以 "segmentation fault"结尾吗?

c - 获取和箭头代码

python - 在垃圾收集中调试 python 段错误

c - 返回 C 中正因子计数的方法

c - 存储许多 for 循环的结果

c - 即使 for 循环计数器值位于数组的 sizeof 之内,但在设置 2d 数组的值时出现段错误

c++ - OpenH264 DecodeFrameNoDelay 输出格式

c - 将 PORTD 值存储在 pic18f452 的数组中 (C)

c - scanf 出现问题