Incrementing an integer value beyond its integer limit - C#
Similar to the behaviour in some implentations of C where an int
just wraps around from INT_MAX to INT_MIN ( though it's actually undefined behaviour according to the ISO standard), C# also wraps. Testing it in VS2008 with:
int x = 2147483647;
if (x+1 < x) {
MessageBox.Show("It wrapped...");
}
will result in the message box appering.
If your hugetValue
is greater than the maximum int
value, then your loop will run forever because of this.
For example, if it's 2147483648
, just as you think you're getting close to it, the int
wraps around from 2147483647
back to -2147483648
and the loop just keeps on going.
Apologies if this seems rude, but you will learn far more by trying this yourself.
Edited: aha, so you did try it, and got unexpected results. As has been explained elsewhere C-like languages tend to quietly wrap integer arithmetic. That's actually quite a reasonable behaviour in general if the cost of checking for overflow is high. Once you know that this can happen one codes carefully, especially watching for the kind of construct in your example.
If you want an exception, either supply the checked
compiler option, or use the checked
construct provided in C#.