If the value after the shift operator
is greater than the number of bits in
the left-hand operand, the result is
undefined. If the left-hand operand is
unsigned, the right shift is a logical
shift so the upper bits will be filled
with zeros. If the left-hand operand
is signed, the right shift may or may
not be a logical shift (that is, the
behavior is undefined).
Can somebody explain me what the above lines mean??
I’m assuming you know what it means by shifting. Lets say you’re dealing with a 8-bit
charsThe first shift, the compiler is free to do whatever it wants, because 9 > 8 [the number of bits in a
char]. Undefined behavior means all bets are off, there is no way of knowing what will happen. The second shift is well defined. You get 0s on the left:11111111becomes00001111. The third shift is, like the first, undefined.Note that, in this third case, it doesn’t matter what the value of
cis. When it refers tosigned, it means the type of the variable, not whether or not the actual value is greater than zero.signed char c = 5andsigned char c = -5are both signed, and shifting to the right is undefined behavior.