简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM