Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise shift operator seems to wrap?

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.

like image 235
Swiss Frank Avatar asked Dec 17 '22 17:12

Swiss Frank


1 Answers

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.

like image 157
PSkocik Avatar answered Dec 20 '22 07:12

PSkocik