Use the unsinged type as operands of shift operator in C language

K&R中如是说:

Right shifting a signed quantity will fill with bit signs (``arithmetic shift'') on some machines and with 0-bits (``logical shift'') on others.

也就说对于负数的右移位,首位补的1 or 0是实现相关的。

我们再来看C99标准:

Image(2)

简而言之,

对于<<, 如果左操作数是signed type, 负数是undefined behavior, 正数如果移位溢出后也是undefined behavior

对于>>, 如果左操作数是singed type, 负数的话其值是implementation-defined.

对于C++2003标准

Image(3)

简而言之,

对于<<, 标准似乎没有定义对于有符号数的情况。

对于>>,标准定义了负数的话,是一个implementation-defined

posted @ 2010-12-27 22:32  嗷嗷  阅读(366)  评论(2编辑  收藏  举报