Blog Post:

Detecting arithmetic overflow in C#

Recently I was interfacing with an accelerometer sensor, and the sensor was streaming raw acceleration values. The C# program processing the data seemed to work as I was getting reasonable output (the output was aggregate of few hundred samples). However while debugging an unrelated problem, I happened to realize that for some streaming values I was having an overflow condition. Although I should have been vigilant, for the present case I found the overflow condition purely by chance. I wasn’t running the debugger because I was getting unexpected results, and what the problem was about I normally wouldn’t be looking at data processing code that had overflows. That made me explore if the C# compiler in Visual Studio 2012 provides any features to detect unsuspecting overflows. I learned that there are two ways for detecting arithmetic overflow in C#.

Configure project build settings

In project properties, go to Build -> Advanced Build Settings and

advanced_build_settings

Use checked/unchecked

The checked/unchecked keyword allows explicit control over the checking of overflow condition for arithmetic operations. If the overflow check is enabled using checked and an overflow condition arises, an OverflowException is thrown. Similarly, the unchecked keyword can be used to disable overflow check for a certain piece of code, if the overflow check is enabled otherwise. The checked/unchecked keywords can be used in expression form or a block form.

The example usage of checked in expression form is:

try
{
Int32 int1 = Int32.MaxValue;
Int32 int2 = checked(int1 + 1);
}
catch (OverflowException ex)
{
Debug.WriteLine(ex.Message);
}

The example usage of checked in block form is

try
{
checked
{
Int32 int1 = Int32.MaxValue;
Int32 int2 = int1 + 1;
}
}
catch (OverflowException ex)
{
Debug.WriteLine(ex.Message);
}

The MSDN documentation for unchecked says the following if performance is a concern:

Because checking for overflow takes time, the use of unchecked code in situations where there is no danger of overflow might improve performance. However, if overflow is a possibility, a checked environment should be used.

Nevertheless I think it is a good idea to do development and testing with overflow check turned on to identify potential overflow issues.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get in Touch

If you have a product design that you would like to discuss, a technical problem in need of a solution, or if you just wish you could add more capabilities to your existing engineering team, please contact us.