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?

Upvotes: 3

Views: 542

Answers (2)

Richard Matheson
Richard Matheson

Reputation: 1175

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.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

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.

Upvotes: 12

Related Questions