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

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

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

11条回答
  •  太阳男子
    2020-11-22 08:48

    Well, I looked it up on wikipedia, and they have this to say:

    C, however, has only one right shift operator, >>. Many C compilers choose which right shift to perform depending on what type of integer is being shifted; often signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.

    So it sounds like it depends on your compiler. Also in that article, note that left shift is the same for arithmetic and logical. I would recommend doing a simple test with some signed and unsigned numbers on the border case (high bit set of course) and see what the result is on your compiler. I would also recommend avoiding depending on it being one or the other since it seems C has no standard, at least if it is reasonable and possible to avoid such dependence.

提交回复
热议问题