Pointer to const object and const pointer

Source: Internet
Author: User

Const char * P1;/pointer to the const object

Char const * P2; // same as above

Char * const P3; // const pointer

Differences: What is after const is limited, for example, char const * P is limited (* P), (* P) is the memory that P points to cannot be changed, and the value of P can be changed, if it is char * const P, It is the value of the P pointer.

1. pointer to the const objectIt is suitable for function parameters and ensures that the pointing object is not modified.

1.1 The value pointed to by P1 cannot be changed, but points to the const object. However, P1 can be modified to point to a non-const object.

Const char C1 = 'C ';

P1 = & C1;

Char C2 = 'D ';

P1 = & C2; // P1 points to a non-const object, but P1 uses * P1 to change its value.

Char * P4 = & C;

P1 = P4;

* P4 = E'; // The P4 object points to the changed object, and P1 points to the object, which is also changed.

1.2 A pointer that does not point to a const object cannot point to a const object

2. Const pointer

2.1 P3 cannot point to another address

Char C3 = 'F ';

P3 = & C3;

Char C4 = 'G ';

Char * P5 = & C4;

P3 = P5; // error. P3 is const and cannot be modified.

C3 = 'H'; // C3 is modified, and the value pointed to by the pointer is also modified.

 

Pointer to const object and const pointer

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.