Different meanings of different const locations

Source: Internet
Author: User

Const & pointer

In the type declaration, const is used to modify a constant. There are two ways to write it. So, what are the following statements that use const to limit immutable content?

1) const is in front

Const int nvalue; // nvalue is const

Const char * Pcontent; // * Pcontent is const, and Pcontent is variable

Const (char *) Pcontent; // Pcontent is const, * Pcontent is variable

Char * const Pcontent; // Pcontent is const, * Pcontent is variable

Const char * const Pcontent; // both Pcontent and * Pcontent are const

2) const is behind and equal to the above statement

Int const nvalue; // nvalue is const

Char const * Pcontent; // * Pcontent is const, and Pcontent is variable

(Char *) const Pcontent; // Pcontent is const, * Pcontent is variable

Char * const Pcontent; // Pcontent is const, * Pcontent is variable

Char const * const Pcontent; // both Pcontent and * Pcontent are const

Answer and analysis:

Using const and pointer together is a common confusion in C language. In actual development, especially when looking at othersCodeIn this case, it is difficult to judge the author's intention. The following describes my judgment principles:

(This rule is wrong.) (because of the appearance of "()", this rule is sometimes invalid .) Draw a line along the number *. If the const is on the left side of *, the const is used to modify the variable pointed to by the pointer, that is, the pointer points to a constant. If the const is on the right side, const is to modify the pointer itself, that is, the pointer itself is a constant. You can view the actual meaning of the above statement based on this rule, and I believe it will be clear at a glance.

In addition, NOTE: For const (char *), because char * is a whole, equivalent to a type (such as char), the pointer is limited to const.

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.