C # Difficulty one by one (7): Checked and unchecked

Source: Internet
Author: User
Tags time 0
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 from a very few expressions, the data is truncated when it is assigned.

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

At this point the available memory stores data to interpret, before int. MaxValue in memory is 32 bit 1, since adding 1 to 32 bit 0, at this time 0 is considered to be a minus sign, so it will get-2147483648.

Placing the above code in the checked block will cause the System.OverflowException type to be thrown.

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 in a checked block throws an exception if the assignment of an overflow occurs at run time.

The unchecked is used to cancel overflow checking of integer arithmetic operations and conversions.

The above is the C # difficulty one by one (7): checked and unchecked content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.