According to cppreference,
For signed
a, the value ofa << bisa * 2^bif it is representable [in the unsigned version of the (since C++14)] return type [(which is then converted to signed: this makes it legal to createINT_MINas1 << 31) (since C++14)], otherwise the behavior is undefined.
I can't quite understand this specification. What does it mean exactly by if it is representable in the unsigned version of the return type? Does it apply only to the case when the signed value is non-negative? Are INT_MIN << 1 and -1 << 31 well-defined?
If we go to source, the C++14 Standard, this is what we find (with the part about unsigned types highlighted):
The value of
E1 << E2isE1left-shiftedE2bit positions; vacated bits are zero-filled. IfE1has an unsigned type, the value of the result isE1 × 2E2, reduced modulo one more than the maximum value representable in the result type. Otherwise, ifE1has a signed type and non-negative value, andE1 × 2E2is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.
For a platform in which std::numeric_limits<int>::digits is 31, it is legal to perform 1 << 31. The resulting value in unsigned int will be 0x80000000 or 2147483648. However, that number is beyond the valid range of value of int for such a platform. However, that bit pattern, when treated as a two's complement representation int is equal to -2147483648, which is the same as INT_MIN for such a platform.
If you use
int a = 2 << 31;
you invoke undefined behavior since 2 * 231 is not representable as an unsigned int in that platform.
Are INT_MIN << 1 and -1 << 31 well-defined?
No, they are not. Bitwise left shifting negative numbers is undefined behavior. Notice the use of non-negative value in the above highlighted text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With