Previous Page
Next Page

Using Checked and Unchecked Integer Arithmetic

In Chapter 2, you learned how to use binary arithmetic operators such as + and * on primitive data types such as int and double. You also saw that the primitive data types have a fixed size. For example, a C# int is 32 bits. Because int has a fixed size, you know exactly the range of value that it can hold: it is –2147483648 to 2147483647.

TIP
If you want to determine the minimum or maximum value of int in code, you can use the Int32.MinValue or Int32.MaxValue fields.

The fixed size of the int type creates a problem. For example, what happens if you add 1 to an int whose value is currently 2147483647? The answer is that it depends on how the application is compiled. By default, the C# compiler generates code that allows the calculation to silently overflow. In other words, you get the wrong answer. (In fact, the calculation wraps around to the largest negative integer value and the result generated is –2147483648.) The reason for this behavior is performance: integer arithmetic is a common operation in almost every program, and adding the overhead of overflow checking to each integer expression could lead to very poor performance. In many cases, the risk is acceptable because you know (or hope!) that your int values won't reach their limits. If you don't like this approach, you can turn on overflow checking by setting.

TIP
You can enable and disable overflow checking in Visual Studio 2005 by setting the project properties. On the Project menu, click YourProject Properties (where YourProject is the name of your project). In the project properties dialog box, click the Build tab. Click the Advanced button in the lower-right corner of the page. In the Advanced Build Settings dialog box, select or clear the “Check for arithmetic overflow/underflow” check box.

Regardless of how you compile an application, you can use the checked and unchecked keywords to selectively turn on and off integer arithmetic overflow checking in parts of an application that you think need it. These keywords override the compiler option.

Writing checked Statements

A checked statement is a block preceded by the checked keyword. All integer arithmetic in a checked statement always throws an OverflowException if an integer calculation in the block overflows, as shown in this example:

int number = Int32.MaxValue; 
checked 
{ 
    int willThrow = number++; 
    Console.WriteLine("this won't be reached"); 
}
IMPORTANT
Only integer arithmetic directly inside the checked block is checked. For example, if one of the checked statements is a method call, the checking does not encapsulate the method call.

You can also use the unchecked keyword to create an unchecked block statement. All integer arithmetic in an unchecked block is not checked and never throws an OverflowException. For example:

int number = Int32.MaxValue; 
unchecked 
{ 
    int wontThrow = number++; 
    Console.WriteLine("this will be reached"); 
}
IMPORTANT
You cannot use the checked and unchecked keywords to control floating point (non-integer) arithmetic. The checked and unchecked keywords control only integer arithmetic. Floating point arithmetic never throws OverflowException—not even when you divide by 0.0 (the .NET Framework has a representation for infinity).
Writing Checked Expressions

You can also use the checked and unchecked keywords to control overflow checking on integer expressions by preceding just the individual parenthesized expression with the checked or unchecked keyword, as shown in this example:

int wontThrow = unchecked(Int32.MaxValue + 1); 
int willThrow = checked(Int32.MaxValue + 1);

The compound operators (such as += and -=) and the increment (++) and decrement (--) operators are arithmetic operators and can be controlled by using the checked and unchecked keywords. Remember, x += y; is the same as x = x + y;.

In the following exercise, you will see how to perform checked arithmetic when using Visual Studio 2005.

Use checked expressions
  1. Return to Visual Studio 2005, and display the MathsOperators solution.

  2. On the Debug menu, click Start Without Debugging.

    You will now attempt to multiply two large values.

  3. Type 9876543 in the left operand text box, type 9876543 in the right operand text box, select the Multiplication option under Operators, and then click Calculate.

    The value –1195595903 appears in the Result text box on the form. This is a negative value, which cannot possibly be correct. This value is the result of a multiplication operation that silently overflowed the 32-bit limit of the int type.

  4. Click Quit to return to the Visual Studio 2005 programming environment.

  5. In the Code pane displaying Form1.cs, locate the multiplyValues method:

    private int multiplyValues(int leftHandSide, int rightHandSide) 
    { 
        expression.Text = leftHandSide.ToString() + " * " + rightHandSide.ToString(); 
        return leftHandSide * rightHandSide; 
    }

    The return statement contains the multiplication operation that is silently overflowing.

  6. Edit the return statement so that the return value is checked. The multiplyValues method should look exactly as follows:

    private int multiplyValues(int leftHandSide, int rightHandSide) 
    { 
        expression.Text = leftHandSide.ToString() + " * " + rightHandSide.ToString(); 
        return checked(leftHandSide * rightHandSide); 
    }

    The multiplication is now checked and will throw an OverflowException rather than silently returning the wrong answer.

  7. In the Code pane, locate the calculate_Click method.

  8. Add the following catch handler immediately after the existing FormatException catch handler in the calculate_Click method:

    catch (OverflowException oEx) 
    { 
        result.Text = oEx.Message; 
    }
    TIP
    The logic of this catch handler is the same as that for the FormatException catch handler. However, it is still worth keeping these handlers separate rather than simply writing a generic Exception catch handler as you might decide to handle these exceptions differently in the future.
  9. On the Debug menu, click Start Without Debugging to build and run the application.

  10. Type 9876543 in the left operand text box, type 9876543 in the right operand text box, select the Multiplication option under Operators, and then click Calculate.

    The second catch handler successfully catches the OverflowException and displays the message “Arithmetic operation resulted in an overflow” in the Result text box.

  11. Click Quit to return to the Visual Studio 2005 programming environment.


Previous Page
Next Page