gpt4 book ai didi

c - a >> ((sizeof a) * CHAR_BIT) 是定义的,UB 还是 IDB?

转载 作者:太空狗 更新时间:2023-10-29 15:24:57 25 4
gpt4 key购买 nike

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

EDIT 已编辑问题

最佳答案

1.

来自 C99 标准,第 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.

所以它是未定义的。

2.

来自同一部分:

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.

所以对于左移,如果 a 是明确定义的已签名且为正。如果 a 则未定义有符号且为负。

对于右移,如果 a 是明确定义的已签名且为正。如果a,它是实现定义的有符号且为负。

关于c - a >> ((sizeof a) * CHAR_BIT) 是定义的,UB 还是 IDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7333025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com