Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is happening when I left shift beyond INT_MAX ?

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?

like image 701
Aks Avatar asked Feb 02 '14 15:02

Aks


1 Answers

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.

like image 64
fede1024 Avatar answered Oct 21 '22 05:10

fede1024