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.
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.
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.
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"); }
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"); }
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.
Return to Visual Studio 2005, and display the MathsOperators solution.
On the Debug menu, click Start Without Debugging.
You will now attempt to multiply two large values.
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.
Click Quit to return to the Visual Studio 2005 programming environment.
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.
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.
In the Code pane, locate the calculate_Click method.
Add the following catch handler immediately after the existing FormatException catch handler in the calculate_Click method:
catch (OverflowException oEx) { result.Text = oEx.Message; }
On the Debug menu, click Start Without Debugging to build and run the application.
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.
Click Quit to return to the Visual Studio 2005 programming environment.