FSMaxB - 9 months ago 43

C Question

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?

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

is`E1 << E2`

left-shifted`E1`

bit positions; vacated bits are filled with zeros. If`E2`

has an unsigned type, the value of the result is`E1`

×`E1`

`2`

^{E2}, reduced modulo one more than the maximum value representable in the result type. Ifhas a signed type and nonnegative value, and`E1`

×`E1`

`2`

^{E2}is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.The result of

is`E1 >> E2`

right-shifted`E1`

bit positions. If`E2`

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`

/`E1`

`2`

^{E2}. Ifhas a signed type and a negative value, the resulting value is implementation-defined.`E1`

Source (Stackoverflow)