Shift Operators in C++

前端 未结 6 1895
傲寒
傲寒 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 12:45

    I suppose the key word is "undefined", which means that the specification does not say what should happen. Most compilers will do something sensible in such cases, but you cannot depend on any behaviour generally. It is usually best to avoid invoking undefined behavior unless the documentation for the compiler you are using states what it does in the specific case.

    The first sentence says it's undefined if you try to shift, for example, a 32 bit value by more than 32 bits.

    The second says that if you shift an unsigned int right, the left hand bits will get filled with zeros.

    The third says that if you shift a signed int right, it is not defined what will be put in the left hand bits.

提交回复
热议问题