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
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
isE1
left-shiftedE2
bit positions; vacated bits are filled with zeros. IfE1
has an unsigned type, the value of the result isE1
x 2E2
, reduced modulo one more than the maximum value representable in the result type. IfE1
has a signed type and nonnegative value, andE1
x 2E2
is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.The result of
E1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient ofE1
/ 2E2
. IfE1
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/