In-depth understanding of the c # checked unchecked keyword

Source: Internet
Author: User
Tags mul

The checked and unchecked keywords are used to restrict the check or do not check the mathematical overflow. If the checked keyword is used, OverflowException is thrown when the mathematical overflow occurs. If the unchecked keyword is used, the overflow is not checked, if it is an error, no error will be reported.
1. A piece of compilation failed code
Copy codeThe Code is as follows: int a = int. MaxValue * 2;

The above code snippet fails to be compiled. in VS2010, there will be a red line indicating a problem with this Code: "The operation overflows at compile time in checked mode ". This indicates that the compiler checks whether the mathematical operation overflows during compilation. However, only constant operations can be used to check for overflow during compilation. The code compiler in 2 does not report any errors.
2. A piece of code that passes compilation but cannot get the correct result
Copy codeThe Code is as follows: int temp = int. MaxValue;
Int a = temp * 2;
Console. Write ();

I will put the constant int first. the value of MaxValue is given to the Temporary Variable temp, and then the Temporary Variable multiplied by 2 is assigned to a. This code can be executed normally, and the execution result is-2.
This indicates that, by default, the program does not check whether the arithmetic operation overflows, And the cpu only performs the calculation. For it, the calculation is based on the rules, and the result is true or false.
The execution is normal and the result is incorrect. This is a very dangerous situation. How can we avoid this danger? See 3
3. Use the checked keyword to trigger an alarm when overflow occurs.
Copy codeThe Code is as follows: int temp = int. MaxValue;
Try
{
Int a = checked (temp * 2 );
Console. WriteLine ();
}
Catch (OverflowException)
{
Console. WriteLine ("overflow, processing ");
}

Use the checked keyword to modify the computing result of temp * 2 and use try catch to handle overflow. The above code will output: "overflow, you need to handle it"
The problem is that if a piece of code requires overflow checks for many arithmetic operations, there will be many checked modified expressions. What should I do? See 4
4. The checked keyword can be used to modify a statement block. See the following code.
Copy codeThe Code is as follows: int temp = int. MaxValue;
Try
{
Checked
{
Int num = temp/20;
Int a = temp * 2;
Int c = temp * 1000;
}
}
Catch (OverflowException)
{
Console. WriteLine ("overflow, processing ");
}

The output result of the above program is the same as that of 3.
5. checked is useful in avoiding Arithmetic overflow. What about unchecked?Is it useful? The answer is yes. Sometimes we don't need accurate computation results. We only need a number. As for overflow, it doesn't matter much. For example, to generate a HashCode for an object, for example, calculating a relative random number based on an algorithm does not require accurate results. The following code snippetCopy codeThe Code is as follows: class Person
{
Public string Name {get; set ;}

Public string Title {get; set ;}

Public override int GetHashCode ()
{
Return unchecked (Name. GetHashCode () + Title. GetHashCode ());
}
}

Unchecked can also modify the statement block, which is exactly the same as checked.
6. checked and unchecked can be nested, although meaningless. Whether the statement is checked depends on the latest nested checked or unchecked.
7. Check the checked keyword from IL
C # code:Copy codeThe Code is as follows: static void Main (string [] args)
{
Int a = int. MaxValue;
Int B = a * 2;
Int c = checked (a * 2 );
Int d = unchecked (a + 3 );

Console. Read ();
}

Corresponding to ILCopy codeThe Code is as follows:. method private hidebysig static void Main (string [] args) di-managed
{
. Entrypoint
// Code size 26 (0x1a)
. Maxstack 2
. Locals init ([0] int32,
[1] int32 B,
[2] int32 c,
[3] int32 d)
IL_0000: nop
IL_0001: ldc. i4 0x7fffffff
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc. i4.2
IL_0009: mul
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldc. i4.2
IL_000d: mul. ovf
IL_000e: stloc.2
IL_000f: ldloc.0
IL_0010: ldc. i4.3
IL_0011: add
IL_0012: stloc.3
IL_0013: call int32 [mscorlib] System. Console: Read ()
IL_0018: pop
IL_0019: ret
} // End of method Program: Main

Please refer to the red and green highlighted display codes in IL. We can see that when checked is used, the IL operation is mul. ovf; when checked is not used or unchecked is used, the IL operation function is mul or add,. ovf.
8. checked or unchecked only affects the statements it is surrounded by. It does not affect the code block that calls the function in the surrounded statement.For example:
Copy codeThe Code is as follows: static void Main (string [] args)
{
Int a = int. MaxValue;
Int B = 20;
Checked
{
Int c = TestMethod (a, B );
Console. WriteLine (c );
}
}

Static int TestMethod (int a, int B)
{
Return a * B;
}

The above code will be executed normally, and the checked statement block does not play its due role.
9. enable or disable the checked compilation option globally
On the project properties page, select the "generate" tab, click the "advanced" button, and select the "check mathematical overflow" option,As follows:

Summary:
Checked and unchecked are two uncommon keywords, but they are useful. Remember to use them when necessary. We recommend that you enable the global checked compiler option during testing. Thank you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.