Integral Overflow – Can you count to 2 Billion?

August 15, 2012

Its probably fair to say that most developers wont encouter a situation requiring a count as 21,474,83647 (Maximum capacity of .Net FrameWork System.Int32).

That said, its probably also fair to say that all developers should be aware of something called ‘Integral Overflow’, which is a behavour of System.Int32, meaning adding to the maximum value, or subtracting from the minimum value, results in an overflow/underflow.

This is demonstrated in the following code:


Int32 intMinVal = Int32.MinValue;
Int32 intMaxVal = Int32.MaxValue;

Debug.WriteLine(intMinVal); // -2147483648
Debug.WriteLine(--intMinVal); // 2147483648 - Underflow

Debug.WriteLine(intMaxVal); // 2147483647
Debug.WriteLine(++intMaxVal); // -2147483647 - Overflow

To prevent this from happening, wrap the code in a checked block. underflow/overflows will then throw an exception


checked
{
Int32 intMinVal = Int32.MinValue;
Int32 intMaxVal = Int32.MaxValue;

Debug.WriteLine(intMinVal);
Debug.WriteLine(--intMinVal); // System.OverflowException

Debug.WriteLine(intMaxVal);
Debug.WriteLine(++intMaxVal); // System.OverflowException
}

As mentoined, this is probably not relevent to the majority of developers. However if you are working with big (Scientific?) data, this may well save yor bacon!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: