C # Difficult to break (7): Checked and unchecked_c# tutorial

Source: Internet
Author: User

C # By default, if the value of a constant expression exceeds the maximum value of the target type, a compilation error will result.

If the target data type cannot hold data for a very few expressions, the data is truncated when it is assigned.

Copy Code code as follows:

Class Program
{
static void Main (string[] args)
{
int n = Int. maxvalue;//n=2147483647
n = n + 1;
System.Console.WriteLine (n);
}
}

At this time the memory is available to store data to interpret before int. MaxValue in memory for 32-bit 1, since the addition of 1 to 32-bit 0, when 0 is considered to be a minus sign, so it will come to-2147483648.

Placing the above code in a checked block will raise the System.OverflowException type.

Copy Code code as follows:

Class Program
{
static void Main (string[] args)
{
Checked
{
int m = Int. MaxValue;
m = m + 1;
System.Console.WriteLine (m);
}
}
}

A variable in C # that is placed inside a checked block throws an exception if an overflow assignment occurs at run time.

unchecked is used to cancel overflow checking of 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.