1

具体的にはこれをやっています

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

この論理シフトの結果は0になると思いますが、代わりに2277を取得しています。Cはこのタイプの操作をどのように定義しますか?

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 に答える