简体   繁体   中英

How does shift operator work with negative numbers in c++

int main() 
{
  int x = -2;

  cout << (1<<x) << endl;

  cout << (1<<-2) << endl;

}

Here the (1<<x) prints 1073741824 (how is this calculated)

Whereas (1<<-2) prints a garbage value.

And why do these two return different answers?

According to the C Standard (6.5.7 Bitwise shift operators)

3 The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. 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

The same is written in the C++ Standard (C++20, 7.6.7 Shift operators)

  1. ... The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the width of the promoted left operand.

In the standard, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3690.pdf

Page 118, Section 5.8.1:

The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand

Meaning the compiler can do whatever it wants here - all bets are off.

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