Q1: The behaviour of the left shift operator on negative values of signed integer types is undefined, as is the behaviour for positive values of signed integer types when the result E1 * 2^E2
is not representable in the type.
That is explicitly mentioned in section 6.5.7, paragraph 4 and 5 of the standard (n1570 draft):
4 The result of E1 << E2
is E1
left-shifted E2
bit positions; vacated bits are filled with zeros. If E1
has an unsigned type, the value of the result is E1 × 2^E2
, reduced modulo one more than the maximum value representable in the result type. If E1
has a signed type and nonnegative value, and E1 × 2^E2
is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
Q2: The reduction modulo one more than the maximum value representable in the unsigned integer type means that the bits that are shifted out on the left are simply discarded.
Mathematically, if the maximal value of the unsigned type is 2^n - 1
(and it is always of that form), the result of shifting E1
left by E2
bits is the value V
in the range from 0 to 2^n - 1
such that the difference
(E1 * 2^E2 - V)
is divisible by 2^n
, that is, it's the remainder you get when dividing E1 * 2^E2
by 2^n
.
Q3: The behaviour upon shifting right negative values of signed integer types is implementation-defined. The most common behaviour (at least on two's complement machines) is an arithmetic shift, that is, the result is the quotient rounded down (towards negative infinity).
5 The result of E1 >> E2
is E1
right-shifted E2
bit positions. If E1
has an unsigned type or if E1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2^E2
. If E1
has a signed type and a negative value, the resulting value is implementation-defined.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…