c++ - 当 b 大于 a 中的位数时右移 (a >> b) 的未定义行为?

标签 c++ c undefined-behavior bit-shift c++14

显然,右移操作的行为:

a >> b
b >= sizeof(a)*CHAR_BIT 时,

在 C 和 C++ 中未定义(而在正常情况下,由于右移而从左侧引入的“新位”等于零)。

b >= sizeof(a)*CHAR_BIT 时,为什么这种未定义的行为比将结果设置为零更好?

最佳答案

我们可以了解为什么语言会从 Why Language Designers Tolerate Undefined Behavior 中选择未定义的行为它说:

This answer came from two general design principles behind C:

  1. The language should impose no unnecessary overhead on the implementation.
  2. It should be as easy as possible to implement C on a wide variety of hardware.

在这种特定情况下,当我们使用大于位宽的移位计数时会发生什么将取决于架构,例如我在 answer here 中解释的那样:

在某些平台上,移位计数将被屏蔽5 位,例如在x86 架构上我们可以看到Intel® 64 and IA-32 Architectures Software Developer’s Manual IA-32 架构兼容性 部分的 SAL/SAR/SHL/SHR—Shift 部分说:

The 8086 does not mask the shift count. However, all other IA-32 processors (starting with the Intel 286 processor) do mask the shift count to 5 bits, resulting in a maximum count of 31. [...]

因此,在某些平台上实现任意计数的移位可能会很麻烦,因此最好保留未定义的行为。

为什么不是未指定的行为

如果我们看一下 Rationale for International Standard—Programming Languages—C它说:

Unspecified behavior gives the implementor some latitude in translating programs. This latitude does not extend as far as failing to translate the program, however, because all possible behaviors are “correct” in the sense that they don’t cause undefined behavior in any implementation.

因此,一定存在或仍然存在行为不正确并且会出现不良问题的情况。

关于c++ - 当 b 大于 a 中的位数时右移 (a >> b) 的未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29136207/

相关文章:

c++ - libjpeg 的输出是否始终为 RGB(或单色图像的亮度)?

c - C 中的有符号和无符号整数

C从字符串中解析一个巨大的int数组

c - 如何将值传递给 XV6 中的系统调用函数?

c++ - 拥有指向保留 vector 元素的指针是否合法?

c++ - 从 DLL 写入控制台

c++ - 如何将 R 的绘图运行到 C/C++ 中?

c++ - 为什么这些示例中的一个是未定义行为而另一个不是?

C++ 头文件 - 包含什么

c++ - 我=我++;未定义。 i = foo(i++) 是否也未定义?