Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding bitwise left shift on signed types in C++14

According to cppreference,

For signed a, the value of a << b is a * 2^b if 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 create INT_MIN as 1 << 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?

like image 459
Lingxi Avatar asked Feb 02 '26 09:02

Lingxi


1 Answers

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 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2E2 , reduced modulo one more than the maximum value representable in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1 × 2E2 is 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.

like image 138
R Sahu Avatar answered Feb 05 '26 04:02

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!