是一个>> ((sizeof a) * CHAR_BIT) 已定义,UB 还是 IDB?
1. 考虑以下问题:
unsigned int a, b;
b = a >> ((sizeof a) * CHAR_BIT);
/* or 2nd operand greater than ((sizeof a) * CHAR_BIT) */
这是已定义的、未定义的行为还是依赖于实现的行为?
2. 还有另一个子问题:
如果a
是signed int
并且它的移位小于其位长度,则有符号移位实现是定义的还是未定义的行为。在这两种情况下:
- 右移时:
a >>> 5
- 左移时:
a << 5
编辑问题已编辑
1.
Consider the following:
unsigned int a, b;
b = a >> ((sizeof a) * CHAR_BIT);
/* or 2nd operand greater than ((sizeof a) * CHAR_BIT) */
Is this is defined, undefined behavior or implementation dependent behavior?
2.
Also another sub-question:
In the case a
is signed int
and it is shifted less than its bit length, is the signed bit shifting implementation defined or undefined behavior. In both the cases:
- When shifting right :
a >> 5
- When shifting left :
a << 5
EDIT question edited
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1.
来自 C99 标准,第 6.5.7 节:
因此它是未定义的。
2.
来自同一部分:
因此,对于左移,如果
a
有符号并且为正,那么它是明确定义的。如果a
有符号并且为负,则它是未定义的。对于右移,
a
是否有符号且为正值是明确定义的。如果a
有符号并且为负,则它是实现定义的。1.
From C99 standard, section 6.5.7:
So it's undefined.
2.
From the same section:
So for left-shift, it's well-defined if
a
is signed and positive. It's undefined ifa
is signed and negative.For right-shift, it's well-defined if
a
is signed and positive. It's implementation-defined ifa
is signed and negative.