Are the shift operators (<<, >>) arithmetic or logical in C?

后端 未结 11 1706
粉色の甜心
粉色の甜心 2020-11-22 07:52

In C, are the shift operators (<<, >>) arithmetic or logical?

11条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 08:44

    In terms of the type of shift you get, the important thing is the type of the value that you're shifting. A classic source of bugs is when you shift a literal to, say, mask off bits. For example, if you wanted to drop the left-most bit of an unsigned integer, then you might try this as your mask:

    ~0 >> 1
    

    Unfortunately, this will get you into trouble because the mask will have all of its bits set because the value being shifted (~0) is signed, thus an arithmetic shift is performed. Instead, you'd want to force a logical shift by explicitly declaring the value as unsigned, i.e. by doing something like this:

    ~0U >> 1;
    

提交回复
热议问题