Warning! In C#, X + 1 does Not Necessarily Equal X + 1

In C#, when you add 1 to the largest value an Int32 can hold, you don’t get an error, you get a wrong answer.

Below, we set max to the largest Int32 value possible. You can see that’s 2,147,483,647, or about 2 billion. But when we add 1 to max we get – 2,147,483,648 — the MinValue for an int! This is what’s known as overflowing. (If we’d added 2, we’d wind up at the MinValue + 1.)

MaxValue + 1 = MinValue!

Fortunately, you can configure your Visual Studio project to catch overflow errors. Right click on your project name and type alt-Enter to bring up the project properties pages. Select the Build tab and scroll down to the bottom right and click the Advanced button. This dialog should open:

Check the “Check for arithmetic overflow/underflow” box. When you run the program again, the overflow exception is caught, and you don’t get a big negative number when you expected a big positive one.

If you want to be more explicit in your code, you can use the checked and unchecked keywords, which will take precedence over whatever’s in the Build settings.

checked
{
    var max = int.MaxValue;
    max++;   // An exception will be thrown because of the "checked" block 
}
unchecked
{
    var max = int.MaxValue;
    max++;   // No exception will be thrown because of the "checked" block 
}

You may want to use a checked wrapper only in cases where you fear an overflow and let the rest of the application remain unchecked. After all, checking is expensive, which is why the setting in Build is off by default.

You may also like...