Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, for example, why is second operand of shift allowed to be signed?

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 positive 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?

like image 384
talkaboutquality Avatar asked Oct 12 '22 07:10

talkaboutquality


1 Answers

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!

like image 92
pmg Avatar answered Oct 15 '22 10:10

pmg