例如,在 C 语言中,为什么允许 shift 的第二个操作数有符号?
注意:这个问题是关于位移运算符 << 的第二操作数的符号性。和>>。与第一个操作数无关。
CERT INT34-C,部分:不要移动负数位......
并不是说它需要理由,但他们证明说这是未定义行为。
我认为该规则是有意义的,因为如果您想以其他方式移位,请使用适当的移位运算符向另一个方向移位正数位。
因此,如果在 C 中,移位负位数既不必要又未定义,为什么 << 的第二个操作数是或>>甚至允许签字?
例如,MISRA-C:2004(无论您喜欢或不喜欢 MISRA)在其第 6.10.2 节中,作为解释结果类型仅取决于第一个操作数的副作用,它说“第二个操作数”操作数可以是任何有符号或无符号整数类型”。 [强调我的]
为什么邀请人们在位移位中使用带符号的第二个操作数?为什么允许呢?有编译器警告它吗?
Note: This question is all about the signedness of the second operand of bit shift operators << and >>. Not at all about the first operand.
CERT INT34-C, in part: Do not shift a negative number of bits ...
Not that it needed justification, but they justify saying that it's undefined behavior.
I would have thought the rule made sense simply because if you want to shift the other way, shift by a positive number of bits using the appropriate shift operator for the other direction.
So if, in C, it is both unnecessary and undefined to shift by a negative number of bits, why is the second operand of << or >> even allowed to be signed?
MISRA-C:2004, for example (whatever you may think of MISRA like or dislike) in its section 6.10.2, as a side effect of explaining that the type of the result depends only on the first operand, says that "the second operand may be of any signed or unsigned integer type". [emphasis mine]
Why invite people to use signed second operand in bit shifting? Why allow it? Do any compilers warn against it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我真的不能说为什么事情是这样的......但我很高兴我可以通过有符号值进行转换:
表达式
a <<= 3;
3 code> 是一个整数。如果按
int
进行移位是非法的,则必须执行a <<= 3U;
。使按有符号值进行移位非法会破坏很多(我的意思是很多)代码!
I can't really say why things are as they are ... but I am glad I can shift by signed values:
3
in the expressiona <<= 3;
is an int.If shifting by an
int
were illegal, you'd have to doa <<= 3U;
.Making it illegal to shift by signed values would break a lot (I do mean A LOT) of code!