是一个>> ((sizeof a) * CHAR_BIT) 已定义,UB 还是 IDB?

发布于 2024-12-03 03:22:47 字数 437 浏览 0 评论 0原文

1. 考虑以下问题:

unsigned int a, b;

b = a >> ((sizeof a) * CHAR_BIT);

/* or 2nd operand greater than ((sizeof a) * CHAR_BIT) */

这是已定义的、未定义的行为还是依赖于实现的行为?

2. 还有另一个子问题:

如果asigned int并且它的移位小于其位长度,则有符号移位实现是定义的还是未定义的行为。在这两种情况下:

  1. 右移时: a >>> 5
  2. 左移时: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:

  1. When shifting right : a >> 5
  2. When shifting left : a << 5

EDIT question edited

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人事已非 2024-12-10 03:22:47

1.

来自 C99 标准,第 6.5.7 节:

对每个操作数执行整数提升。结果的类型是
提升后的左操作数。 如果右操作数的值为负数或
大于或等于提升的左操作数的宽度,行为未定义

因此它是未定义的。

2.

来自同一部分:

E1 << 的结果E2E1 左移 E2 位位置;空出的位用零填充。如果 E1 为无符号类型,则结果值为 E1 x 2E2,再模 1 减少大于结果类型中可表示的最大值。 如果 E1 具有带符号类型和非负值,并且 E1 x 2E2 可以表示为result类型,那么就是结果值;否则,行为未定义。

E1>>的结果E2E1 右移的 E2 位位置。如果E1具有无符号类型或如果E1具有有符号类型和非负值,则结果的值是商的整数部分>E1 / 2E2如果 E1 具有带符号类型和负值,则结果值由实现定义

因此,对于左移,如果 a 有符号并且为正,那么它是明确定义的。如果 a 有符号并且为负,则它是未定义的。

对于右移,a 是否有符号且为正值是明确定义的。如果 a 有符号并且为负,则它是实现定义的。

1.

From C99 standard, section 6.5.7:

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.

So it's undefined.

2.

From the same section:

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 x 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 x 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

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 nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

So for left-shift, it's well-defined if a is signed and positive. It's undefined if a is signed and negative.

For right-shift, it's well-defined if a is signed and positive. It's implementation-defined if a is signed and negative.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文