This is Windows 7 32-bit, Visual Studio 2017, in a C file.
int i = 65536;
As expected,
i >> 0 = 65536
i >> 1 = 32768
:
:
i >> 16 = 1
i >> 17 to 31 = 0.
i >> 32 is magically 65536 again though. How is that legal?
ISO/IEC 9899:TC2 says the following and I assume C++ specs are the same?
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.
6.5.7p3
... If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
With clang, gcc, and icc, you'll get a warning if you attempt to shift by a constant that's greater or equal to the width of the shifted value, and you don't even need any extra command-line flags.
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