I know that this is undefined:
uint32_t u = 1;
u << 32;
But I'm a little bit confused about which kinds of shifts are undefined.
Is it undefined to shift a signed integer by it's size (in bits) or more to the right?
Update: As pointed out in the answer, this is about the size in bits, not in bytes.
sizeof (int)
is the size of int
in bytes, so it's not relevant. What's relevant is not the size, but the width, which is the number of value bits in the representation (plus the sign bit for signed types).
If the right operand of a <<
or >>
operator is greater than or equal to the width of the promoted left operand, the behavior is undefined. (For example, if the left operand is of type short
, it's promoted to int
before the operation is applied).
For the <<
left-shift operator, the behavior is defined only if the left operand is non-negative and the result is representable.
For the >>
right-shift operator, the result is implementation-defined if the left operand is negative.
This is all defined in section 6.5.7 of the C standard (the link is to N1570, the most recent publicly available C11 draft).
Here's the full description of the semantics:
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.
The result of
E1 << E2
isE1
left-shiftedE2
bit positions; vacated bits are filled with zeros. IfE1
has an unsigned type, the value of the result isE1
×2
E2
, reduced modulo one more than the maximum value representable in the result type. IfE1
has a signed type and nonnegative value, andE1
×2
E2
is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.The result of
E1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient ofE1
/2
E2
. IfE1
has a signed type and a negative value, the resulting value is implementation-defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With