Controlling arithmetic overflow

By DimitriC at March 04, 2010 12:25
Filed Under: Programming

To let the .Net framework check for overflows, you can use the /checked+ switch when compiling your software. This switch will let the compiler know that it has to generate extra overflow-checks for the multiply, add, subtract and conversion IL-instructions (IL = Intermediate Language). If an overflow occurs, you will get an OverflowException. Of course, this has an impact on performance.

 

To counter this extreme action (the overflow-check is either enabled or disabled for you entire application) you might want to add your own checks in places in your application where you know an overflow might occur. C# provides two keywords to do this: checked and unchecked. When using checked and exception will be thrown, when using unchecked the arithmetic overflow is ignored and the result is truncated.

 

Do note that not only explicit numeric conversions between integers are affected. The following expressions are also affected by the overflow checking: ++, – (double minus), – (unary) , +, –, *, /.

 

On MSDN there is a very clear sample that illustrates these two keywords: checked and unchecked.

 

In Jeffery Richter’s book “CLR via C#, Second Edition”, Chapter 5: Primitive, Reference, and Value Types you can also find information about this subject.

Comments are closed