FSMaxB FSMaxB - 2 months ago 10
C Question

Is rightshifting signed int by 8 * sizeof(int) or more undefined?

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.

Answer

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 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

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.

Comments