Const and pointer (pointer to const object, const pointer)

Source: Internet
Author: User

1. pointer to the const object

Const int * P;
This P is a pointer to an int-type const object. Const limits the type pointed to by the pointer P rather than P itself. That is to say, P itself is not a const. You do not need to initialize it during definition. You can also assign a value to P to point it to another const object. However, you cannot use P to modify the value of the object to be pointed.
Example 1: int A = 0; P = & A; yes.
Example 2: * P = 20; No.
Conclusion: This pointer to a const object only limits the number of objects that P points to, rather than the object to which P points.

It is not acceptable to assign the address of a const object to a pointer that does not point to a const object.
Example 3: const int B = 10;
Int * P2 = & B; // Error
Const int * P3 = & B; // OK
Conclusion: Variable B cannot be modified because it has const modification. However, pointer P2 is a common pointer and can be used to modify the value pointing to an object. The two statements are conflicting, so it is invalid. The pointer to the const object cannot modify the value of the pointer to the object. Therefore, this method is valid.

2. Const pointer

Int c = 20;
Int * const P4 = & C;

Pointer p4 is called a const pointer. It is the opposite of a pointer to a const object. It cannot modify the value pointing to an object, but can modify the value pointing to an object. In addition, this pointer must be initialized during declaration.

3. Const pointer to the const object

Const int d = 30;
Const int * const dp = & D;

The pointer DP neither modifies the object to which it points nor modifies the value of the object to which it points.

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.