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标准:

Use the unsinged type as operands of shift operator in C language_第1张图片

简而言之,

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

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

对于C++2003标准

Use the unsinged type as operands of shift operator in C language_第2张图片

简而言之,

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

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

你可能感兴趣的:(language)