What is happening when I left shift beyond INT_MAX ?

bit-manipulation, c++

Solution

You have a signed int, so numbers are in two's complement. This is what happens

00..01 = 1
00..10 = 2
[...]
01..00 = 1073741824
10..00 = -2147483648 // Highest bit to one means -01..11 - 1 = -(2^31)
00..00 = 0

You cannot reach INT_MAX, at most you will have `2^30`.

As pointed out in the comments, c++ standard does not enforce 2's complement, so this code could behave differently in other machines.

Problem

I have this piece of code ``` int a = 1; while(1) { a<<=1; cout<<a<<endl; } ``` In the output, I get ``` . . 536870912 1073741824 -2147483648 0 0 ``` Why am I not reaching INT_MAX? and what is really happening beyond that point?

Original source

Related problems