What happens when you bit shift beyond the end of a variable?

后端 未结 3 1140
野的像风
野的像风 2020-12-04 00:18

If you have some variable (on the stack) and you left or right bit shift beyond its end what happens?

i.e.

byte x = 1;
x >> N;
<
3条回答
  •  Happy的楠姐
    2020-12-04 00:34

    I think you're confused. x >> y does not actually change x in the first place. It calculates a new value.

    As Stephen noted, y must not be negative, and it must be less than "the width of the promoted left operand" (read up on type promotion). But otherwise, bits that shift "off the end" are simply discarded. 1 >> 2 (notice that 2 is not negative, and it is less than the number of bits used to represent 1, which is probably 32 but certainly at least 16) evaluates to 0.

提交回复
热议问题