C # difficulties 1 by 1 (7): checked and unchecked

Source: Internet
Author: User

C # by default, if the constant expression value exceeds the maximum value of the target type, compilation errors will occur.

If the target data type cannot contain data of a non-numeric expression, the data will be truncated when the value is assigned.

CopyCodeThe Code is as follows: Class Program
{
Static void main (string [] ARGs)
{
Int n = int. maxvalue; // n = 2147483647
N = n + 1;
System. Console. writeline (N );
}
}

In this case, the memory storage data can be used to explain the preceding Int. the value of maxvalue is in the memory of 32-bit 1 and changes to 32-Bit 0 after the auto-increment is 1. In this case, 0 is regarded as a negative number, so-2147483648 is obtained.

Placing the above Code in the checked block will lead to the system. overflowexception type.

Copy codeThe Code is as follows: Class Program
{
Static void main (string [] ARGs)
{
Checked
{
Int M = int. maxvalue;
M = m + 1;
System. Console. writeline (m );
}
}
}

C # is placed in the checked block. If an overflow value is assigned during running, an exception is thrown.

UncheckedUsed to cancel overflow checks for integer arithmetic operations and conversions.

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.