Is there a difference between bitshift by a constant versus bitshifting by a variable with the same value, in C?

bit-shift, c

Solution

It is undefined behavior to shift by the bit length of a variable or greater. From the draft C99 standard section `6.5.7` Bitwise shift operators:

[...]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.

As Pascal says, you need to make a special case or use a wider type.

`gcc` in some cases can generate a warning for this see it live:

warning: left shift count >= width of type [enabled by default]

Problem

I'm attempting to bitshift the value `0xFFFFFFFF` by 32 bits, and it correctly comes to 0 if I write ``` x = x << 32; ``` however it stays as `0xFFFFFFFF` when I write: ``` x = x << y ``` when `y = 32` I really don't understand this at all. I need to be able to use a variable though, for a function that shifts by `32 - n` Edit If `<< 32` is undefined, then I really can't perceive a way to create a function that pads n - upper bits with 1's

Original source