最近在看Core Java 第三章讲右移运算符>>中,强调了c/c++和java的不同,对于java右移运算,高位是用符号位进行填充,那么对于负数的右移是用1来填充,因此
|
|
书中说对于c/c++,是不确定的,如果对于非负数是没有歧义的,但是对于负数,是用0还是1来填充会选择效率高的一种执行,也就是说结果是未定义的,也可以理解成c/c++中>>只是为非负数定义的
查阅了cpp reference
For negative
a, the behavior ofa << bis undefined.For unsigned
aand for signedawith nonnegative values, the value ofa >> bis the integer part of a/2b
. For negativea, the value ofa >> bis implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative).In any case, if the value of the right operand is negative or is greater or equal to the number of bits in the promoted left operand, the behavior is undefined.
也得到了印证,所以在c/c++中要对负数右移操作慎用。