Checked and unchecked primitive type operations

Source: Internet
Author: User
Tags mul

Many of the arithmetic operations performed on primitive types can cause overflow:

+//  B now contains 44 (or hexadecimal value 2C) 

Important: When performing the above arithmetic operations, the first step requires that all operands be expanded to 32-bit values (or 64-bit values if any operand needs to be represented by more than 32 bits). SobAnd $(Both values are not more than 32 bits) are first converted to 32-bit values and then added together. The result is a 32-bit value (decimal 300, or hexadecimal 12C). The value is stored back in the variablebBefore it must be transformed into aByte
C # does not implicitly perform this transformation operation, which is exactly the second line of code that needs to be cast toByteThe reason.
In most programming scenarios, this kind of quiet overflow is something we don't want. If this overflow is not detected, it can cause the application to behave erratically. But in very few programming scenarios, such as calculating a hash value or checksum, this overflow is not only acceptable, but we want it to be.
Different languages handle overflows in different ways. C and C + + do not treat overflows as errors and allow values to be rolled back (wrap) 39; The application will run "as it should". Instead, Microsoft Visual Basic always treats overflows as errors and throws an exception when an overflow is detected.
The CLR provides special IL directives that allow the compiler to choose the behavior it deems most appropriate. The CLR has aAddInstruction that adds two values together, but does not perform an overflow check. The CLR also has aadd.ovfinstruction, the effect is to add two values together, but will throw an overflowSystem.OverflowExceptionAbnormal. In addition to these two IL directives for addition operations, the CLR provides similar il directives for subtraction, multiplication, and data conversions, respectivelysub/sub.ovfmul/mul.ovfAndconv/conv.ovf
C # allows programmers to decide for themselves how to handle overflows. The overflow check is turned off by default. That is, the compiler automatically uses the version of the add, subtract, multiply, and convert directives that do not contain overflow checking when generating IL code. The result is that the code can run faster-but developers must ensure that no overflow occurs, or that their code can anticipate these overflows.
One way to let the C # compiler control overflow is to use the/checked+The compiler switch. This switch instructs the compiler to use the overflow check version of the Add, subtract, multiply, and convert directives when generating code. This generates code that is slightly slower to execute because the CLR checks these operations to determine if an overflow occurs. If an overflow occurs, the CLR throws aOverflowExceptionAbnormal.
In addition to globally turning overflow checking on or off, programmers can control overflow checking in specific areas of the code. C # by providingcheckedAnduncheckedoperator to achieve this flexibility. The following is a use of auncheckedExamples of operators:

unchecked ((UInt32) (-1));  // OK

The following example uses the checked operator:

   checked//throw OverflowException exception

In this example, b and C are first converted to 32-bit values and then added together, and the result is 300. Then, because of the existence of an explicit transformation, it is converted to a Byte, which causes a OverflowException exception. If Byte is outside the checked operator, the
Type, the exception does not occur:

checked  $ // b contains 44; OverflowException exception is not thrown

In addition to the checked and unchecked operators, C # also supports checked and unchecked statements, They cause all expressions in a block to be checked without overflow:

checked // start a checked block  -  //  the expression will overflow check  //

In fact, if you use a checked statement block, you can use the + = operator for Byte, simplifying the code a little bit:

checked // start a checked block  -  $//  the expression will overflow check }

Important: Because the checked operator and the checked statement are the only thing that determines which version of the add, subtract, multiply, and data conversion IL directives are generated, in a checked An operator or a statement calls a method without any effect on the method.

Important NOTES:
System.DecimalThe type is a very special type. While many programming languages, including C # and Visual Basic, willDecimalis treated as a primitive type, but the CLR is not. This means that the CLR does not have a corresponding IL directive to determine how to handle aDecimalValue. View in the. NETFramework SDK DocumentationDecimalType can be seen, it provides a series ofPublic Staticmethods, includingADDSubtractMultiplyDividesuch as BesidesDecimalThe type is also +,-, *,/etc. provided with operator overloading methods.
Compilation uses theDecimalValue of the program, the compiler generates code to invoke theDecimalMembers and perform the actual operation through these members. This means thatDecimalThe processing speed of the value is slower than the value of the CLR primitive type. Also, because there is no corresponding IL directive to handleDecimalValue, socheckedAnduncheckedOperators, statements, and compiler switches are useless. If the
DecimalThe operation of the value execution is unsafe and will certainly throw aOverflowExceptionAbnormal.
In a similar way,System.Numerics.BigIntegerType is also used internally by aUInt32Array to represent an arbitrarily large integer whose value has no upper and lower bounds. Therefore, theBigIntegerThe operation performed will never causeOverflowExceptionAbnormal. However, if the value is too large and there is not enough memory to change the size of the array, theBigIntegerOperation May throw aOutOfMemoryExceptionAbnormal.



Checked and unchecked primitive type operations

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.