C# provides the checked and unchecked keywords to enable and disable overflow checking for integer arithmetic. It might surprise you to know that Visual Studio C# projects disable overflow checking by default. Consider the following example:
var a = int.MaxValue; Console.WriteLine(++a);
With the default project settings this code will output –2147483648 instead of throwing an OverflowException. Personally I think overflow checking should be enabled by default since overflow is rarely intentional and when it is, well that’s what the unchecked keyword is for. Fortunately changing the default behaviour for Visual Studio C# projects is straightforward. Open the project properties page, select the Build tab and click the Advanced… button.
Check the Check for arithmetic overflow/underflow check box in the resulting dialog as shown above. I’d recommend doing this for all of your build configurations.
Cheers. Hit that problem the other day and was surpirsed that the count just wrapped.
ReplyDelete