Shift Operators in C++

前端 未结 6 2009
傲寒
傲寒 2020-12-09 12:17

If the value after the shift operator is greater than the number of bits in the left-hand operand, the result is undefined. If the left-hand operand is

6条回答
  •  悲哀的现实
    2020-12-09 13:01

    I'm assuming you know what it means by shifting. Lets say you're dealing with a 8-bit chars

    unsigned char c;
    c >> 9;
    c >> 4;
    signed char c;
    c >> 4;
    

    The first shift, the compiler is free to do whatever it wants, because 9 > 8 [the number of bits in a char]. Undefined behavior means all bets are off, there is no way of knowing what will happen. The second shift is well defined. You get 0s on the left: 11111111 becomes 00001111. The third shift is, like the first, undefined.

    Note that, in this third case, it doesn't matter what the value of c is. When it refers to signed, it means the type of the variable, not whether or not the actual value is greater than zero. signed char c = 5 and signed char c = -5 are both signed, and shifting to the right is undefined behavior.

提交回复
热议问题