Note: This question is all about the signedness of the second operand of bit shift operators << and >>. Not at all about the first operand.
CERT INT34-C, in part: Do not shift a negative number of bits ...
Not that it needed justification, but they justify saying that it's undefined behavior.
I would have thought the rule made sense simply because if you want to shift the other way, shift by a posi开发者_如何学Gotive number of bits using the appropriate shift operator for the other direction.
So if, in C, it is both unnecessary and undefined to shift by a negative number of bits, why is the second operand of << or >> even allowed to be signed?
MISRA-C:2004, for example (whatever you may think of MISRA like or dislike) in its section 6.10.2, as a side effect of explaining that the type of the result depends only on the first operand, says that "the second operand may be of any signed or unsigned integer type". [emphasis mine]
Why invite people to use signed second operand in bit shifting? Why allow it? Do any compilers warn against it?
I can't really say why things are as they are ... but I am glad I can shift by signed values:
3
in the expression a <<= 3;
is an int.
If shifting by an int
were illegal, you'd have to do a <<= 3U;
.
Making it illegal to shift by signed values would break a lot (I do mean A LOT) of code!
精彩评论