Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does shifting more than the allowed bits still work?

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?

like image 294
user2030677 Avatar asked Jan 14 '23 20:01

user2030677


1 Answers

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

like image 94
NPE Avatar answered Jan 21 '23 10:01

NPE