C # const detailed analysis and description

Source: Internet
Author: User

Const is a key word in C language. It specifies that a variable cannot be changed. Using const can improve the security and reliability of the program to a certain extent. In addition, it is helpful to understand the role of const while watching other people's code. In addition, const also appears in other programming languages, such as c ++, php tutorial 5, c #. net, hc08 c

The variable modified by const is a read-only variable.

The const definition should be that its value cannot be changed after initialization.

For example, const int a = 1; // It can only be initialized during definition;

A = 2; // an error occurs because a is a read-only variable.

Usage of const when modifying some pointers

Int;

Const int * p = & a; // * p cannot be changed, but p can be changed.

Int * const p1 // defines a read-only variable p1; p1 cannot be changed * p1 can be changed


A constant declaration can declare multiple constants, for example, public const double x = 1.0, y = 2.0, z = 3.0; static modifiers cannot be used in a constant declaration. Constants can be involved in constant expressions, as shown below: public const int c1 = 5; public const int c2 = c1 + 100; note that the readonly keyword is different from the const keyword. The const field can only be initialized in the declaration of this field. The readonly field can be initialized in the Declaration or constructor. Therefore, the readonly field may have different values based on the constructors used. In addition, the const field is the compile time, while the readonly field can be used for the run time, as shown in the following code line: public static readonly uint l1 = (uint) datetime. now. ticks;

 

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.