简体   繁体   中英

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

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

ie

byte x = 1;
x >> N;

What if x is a pointer 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.

You get zero. No wrapping into other memory locations. You may as well have cleared it.

It just becomes all zero. So whatever it's length was but in zeroes.

ie say the binary is 001, after 3 bit shifts it would just be 000. No wrap around occurs and it doesn't move the location (unless you are bit shifting the pointer itself and then I have no idea).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM