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

后端 未结 3 1137
野的像风
野的像风 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条回答
  •  离开以前
    2020-12-04 00:45

    I think you're confused about what bitshifts do. They are arithmetic operators equivalent to multiplication or division by a power of 2 (modulo some weirdness about how C treats negative numbers). They do not move any bits in memory. The only way the contents of any variable/memory get changed are if you assign the result of the expression back somewhere.

    As for what happens when the righthand operand of a bitshift operator is greater than or equal to the width of the type of the lefthand expression, the behavior is undefined.

提交回复
热议问题