What happens when I go beyond INT_MAX?

I have this piece of code

int a = 1; while(1) { a<<=1; cout<<a<<endl; } 

At the output, I get

 . . 536870912 1073741824 -2147483648 0 0 

Why am I not getting to INT_MAX? and what really happens outside of this moment?

+6
source share
4 answers

You have a signed int, so the numbers are in two additions. Here's what's going on

 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 contact INT_MAX, at best you will have 2^30 .

As stated in the comments, the C ++ standard does not use 2 add-ons, so this code may behave differently on other machines.

+12
source

From ISO / IEC 14882: 2011 Clause 5.8 / 2

The value of E1 <E2 is the left shifted position of E2; freed bits are filled with zeros. If E1 has an unsigned type, the result value is E1 Γ— 2 E2 reduced by one more than the maximum value represented in the result type. Otherwise, if E1 has a signed type and a non-negative value, and E1 Γ— 2 E2 is represented in the result type, then this is the resulting value; otherwise the behavior is undefined

+7
source

According to the C ++ standard:

Undefined behavior if the right operand is negative or greater than or equal to the bit length of the advanced left operand

In the example, when you shift the number to the left, the freed bits are filled with zeros. As you can see, all your numbers are equal. This is due to the fact that the least significant bits are filled with zero. You must write:

 a = ( a << 1 ) | 1; 

if you want to get INT_MAX . Also, the loop should check if the number is positive.

+2
source

Take a look at this (link) [http://www.cplusplus.com/reference/climits/]: Assuming INT_MAX == 2^15-1 , executing the loop as you do, you will get 2^14 , 2^15 and 2^16 , but 2^15-1 , never. But INT_MAX are different (see ref, or greater link), try this on your computer:

 #include<climits> #include<iostream> int main(){ int a = 1; int iter = 0; std::cout << "INT_MAX == " << INT_MAX << " in my env" << std::endl; while(1) { a <<=1; std::cout << "2^" << ++iter << "==" << a << std::endl; if((a-1) == INT_MAX){ std::cout << "Reach INT_MAX!" << std::endl; break; } } return 0; } 

See how INT_MAX, 2^exp - 1 .

+2
source

All Articles