4

I have an int8_t and I wanted to see what would happen if I shift it left further than 8 bits. So this is what I did:

int8_t x = 1;

std::cout << (x << 10);

For some reason this returns 1024 as if the type contained enough bits to represent that number. I thought that when you shift more than the given bits you would get 0 in all the bits (or signed overflow/underflow which leads to undefined behavior). Also, I ran this code to give me the maximum number of int8_t:

std::numeric_limits<int8_t>::max(); // 127

The max number of this type is 127 but shifting it left can make it even go higher than its unsigned type! How is this possible?

user2030677
  • 3,448
  • 4
  • 23
  • 36

1 Answers1

9

The arguments to << are being implicitly widened to int, and the result of x << 10 is also an int.

NPE
  • 486,780
  • 108
  • 951
  • 1,012