Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Surprisingly, the first line throws mentioned error. But the for loop works. For loop executed too and performs addition as well. It seems as if we are moving in circles while dealing with integers. Any insight on why this happens?

C#
// int i = int.MaxValue + 100; // Error: The operation overflows at compile time in checked mode
// Following works
for (int i = int.MaxValue; i > 0; i++)
{
  i = i + 10;

  Console.WriteLine(i);
}
Posted

Because integers do indeed move in circles! If you exceed the MaxValue, then you get into negative territory. Anything with the top bit set in a signed integer is a negative number, and the Max value is a single 0 bit in an otherwise 1 filled 32 bit word. If you add a value to that, then the new value will have the top bit set, and thus be negative.
It's a little annoying that it doesn't throw an overflow exception, but that's life!

The other line complains at compile time because it rightly spots that if you add a number to it's maximum value, it will overflow.
 
Share this answer
 
Comments
BobJanova 23-Aug-11 4:52am    
If it annoys you, you can put the calculation inside checked { ... }. Sometimes either one is useful.
Prerak Patel 23-Aug-11 4:53am    
Is that so? I think it is because wrong increment in loop. i-- will get the inside statement execute, and throw the exception. At least, in VB, it does.
dan!sh 23-Aug-11 6:04am    
Nice explanation. Thanks
What do you mean with 'works'? It silently overflows, that's all.
 
Share this answer
 
Comments
dan!sh 23-Aug-11 5:42am    
And that's weird. We, a developer, may miss out on this kind of thing which can result in huge problems.
CPallini 23-Aug-11 5:48am    
well, we're developers, not spoon-fed children.

dan!sh 23-Aug-11 6:05am    
Not everyone is. :)
MaxValue +1 == Maxvalue *-1;

So when it is at the top it will return to the maximum negative value in the Int range
 
Share this answer
 
Just put i-- and it will overflow. :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900