1

Specifically I am doing this

Word32 x = 18653184;
Word32 y;
Word16 shift = 269;
y = x >> shift;

I'd expect the result of this logical shift to be 0, but I am instead getting 2277. How does C define this type of operation?

4

2 回答 2

5

Yes, it is undefined behavior, according to section 6.5.7 paragraph 3

... 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.

于 2012-12-04T16:35:44.643 回答
3
ISO c99 : 6.5.7 Bitwise shift operators

3
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.

5
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

You can see c-standard clarifies everything.

于 2012-12-04T16:35:47.587 回答