当b大于a中的位数时,右移(a >> b)的不确定行为. [英] Undefined behaviour of right shift (a >> b) when b is greater than the number of bits in a?

查看:93
本文介绍了当b大于a中的位数时,右移(a >> b)的不确定行为.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,右移操作的行为:

Apparently, the behaviour of the right shift operation:

a >> b

b >= sizeof(a)*CHAR_BIT时,

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

is undefined in C and C++ when b >= sizeof(a)*CHAR_BIT (whereas in the normal case, the "new bits" introduced from the left due to the right shift are equal to zero).

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

Why is this undefined behaviour better than setting the result to zero when b >= sizeof(a)*CHAR_BIT?

推荐答案

我们可以从

此答案来自C背后的两个通用设计原则:

This answer came from two general design principles behind C:

  1. 该语言不应在实现上增加不必要的开销.
  2. 在各种硬件上实现C应该尽可能容易.

在这种特定情况下,当我们使用比位宽大的移位计数时会发生什么情况将取决于体系结构,例如我在

in this specific case what happens when we use a shift count larger than the bit width will depend on the architecture for example as I explain in my answer here:

在某些平台上,移位计数将被掩盖5 bits,例如在x86架构上,我们可以看到

on some platforms the shift count will be masked to 5 bits for example on an x86 architecture we can see the Intel® 64 and IA-32 Architectures Software Developer’s Manual section SAL/SAR/SHL/SHR—Shift in the IA-32 Architecture Compatibility section says:

8086不会掩盖移位计数.但是,所有其他IA-32处理器(从Intel 286处理器开始)都将移位计数屏蔽为5位,从而导致最大计数为31.[...]

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. [...]

因此,在某些平台上实现任意数量的移位可能会很麻烦,因此最好使其保持未定义的状态.

So implementing shift for an arbitrary count may be burdensome on some platforms and therefore it is better to leave it undefined behavior.

为什么不是未指定的行为

如果我们查看国际标准准则—编程语言— 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.

因此,肯定有一个案例,或者仍然存在一个案例,该案例的行为不是正确,并且存在严重问题.

So there must have been a case or still exists a case where the behavior is not correct and would have bad issues.

这篇关于当b大于a中的位数时,右移(a >> b)的不确定行为.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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