Danh mục tài liệu

Using Checked and Unchecked Integer Arithmetic

Số trang: 4      Loại file: pdf      Dung lượng: 14.65 KB      Lượt xem: 6      Lượt tải: 0    
Xem trước 2 trang đầu tiên của tài liệu này:

Thông tin tài liệu:

Sử dụng kiểm tra và đánh dấu Integer số học Trong chương 2, bạn đã học cách sử dụng toán tử số học nhị phân chẳng hạn như + và * trên dữ liệu các loại nguyên thủy như int và tăng gấp đôi. Bạn cũng thấy rằng các loại dữ liệu nguyên thủy có kích thước cố định. Ví dụ, một C # int là 32 bit.
Nội dung trích xuất từ tài liệu:
Using Checked and Unchecked Integer ArithmeticUsing Checked and Unchecked Integer ArithmeticIn Chapter 2, you learned how to use binary arithmetic operators such as + and * onprimitive data types such as int and double. You also saw that the primitive data typeshave a fixed size. For example, a C# int is 32 bits. Because int has a fixed size, you knowexactly the range of value that it can hold: it is –2147483648 to 2147483647.TIPIf you want to determine the minimum or maximum value of int in code, you can use theInt32.MinValue or Int32.MaxValue fields.The fixed size of the int type creates a problem. For example, what happens if you add 1to an int whose value is currently 2147483647? The answer is that it depends on how theapplication is compiled. By default, the C# compiler generates code that allows thecalculation to silently overflow. In other words, you get the wrong answer. (In fact, thecalculation wraps around to the largest negative integer value and the result generated is –2147483648.) The reason for this behavior is performance: integer arithmetic is acommon operation in almost every program, and adding the overhead of overflowchecking 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 wont reach theirlimits. If you dont like this approach, you can turn on overflow checking by setting.TIPYou can enable and disable overflow checking in Visual Studio 2005 by setting theproject properties. On the Project menu, click YourProject Properties (where YourProjectis 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 BuildSettings dialog box, select or clear the “Check for arithmetic overflow/underflow” checkbox.Regardless of how you compile an application, you can use the checked and uncheckedkeywords to selectively turn on and off integer arithmetic overflow checking in parts ofan application that you think need it. These keywords override the compiler option.Writing checked StatementsA checked statement is a block preceded by the checked keyword. All integer arithmeticin a checked statement always throws an OverflowException if an integer calculation inthe block overflows, as shown in this example:int number = Int32.MaxValue;checked{ int willThrow = number++; Console.WriteLine(this wont be reached);}IMPORTANTOnly integer arithmetic directly inside the checked block is checked. For example, if oneof the checked statements is a method call, the checking does not encapsulate the methodcall.You can also use the unchecked keyword to create an unchecked block statement. Allinteger arithmetic in an unchecked block is not checked and never throws anOverflowException. For example:int number = Int32.MaxValue;unchecked{ int wontThrow = number++; Console.WriteLine(this will be reached);}IMPORTANTYou cannot use the checked and unchecked keywords to control floating point (non-integer) arithmetic. The checked and unchecked keywords control only integerarithmetic. Floating point arithmetic never throws OverflowException—not even whenyou divide by 0.0 (the .NET Framework has a representation for infinity).Writing Checked ExpressionsYou can also use the checked and unchecked keywords to control overflow checking oninteger expressions by preceding just the individual parenthesized expression with thechecked 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 andunchecked keywords. Remember, x += y; is the same as x = x + y;.In the following exercise, you will see how to perform checked arithmetic when usingVisual 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:6. private int multiplyValues(int leftHandSide, int rightHandSide)7. {8. expression.Text = leftHandSide.ToString() + * + rightHandSide.ToString();9. return leftHandSide * rightHandSide; } The return statement contains the multiplication operation that is silently overflowing.10. Edit the return statement so that the return value is checked. The multiplyValues method should look exactly as follows:11. private int multiplyValues(int leftHandSide, int rightHandSide)12. {13. expression.Text = leftHandSide.ToString() + * + rightHandSide.ToString();14. return checked(leftHandSide * rightHandSide); } The multiplication is now checked and will throw an OverflowException rather than silently returning the wrong answer.15. In the Code pane, locate the calculate_Click method.16. Add the following catch handler immediately after the existing FormatException catch handler in the calculate_Click method:17. catch (OverflowException oEx)18. {19. result.Text = oEx.Message; } TIP The logic of this catch handler is the same as that for the FormatExcepti ...