开发者

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

开发者 https://www.devze.com 2023-01-28 02:39 出处:网络
If you have some variable (on the stack) and you left or right bit shift beyond its end what happens?

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;

What if x is a pointe开发者_开发知识库r to memory cast to a byte and you do the same thing?

byte* x = obtain pointer from somewhere;
*x = 1;
*x >> N;


It does not (necessarily) become zero. The behavior is undefined (C99 §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.

(C++0x §5.8, "Shift operators"):

The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

The storage of the value being shifted has no effect on any of this.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消