A simple memory method for const * and * const and const to modify pointers

Source: Internet
Author: User
We can refer to the practice on item21 in Objective C ++. If const is on the left side of the asterisk, const is used to modify the variable pointed to by the pointer, that is, the pointer points to a constant; if const is on the right side of the asterisk, const modifies the pointer itself, that is, the pointer itself is a constant.

For example:

# Include <iostream>

Using namespace STD;

Int main ()

{

Int A = 3, B = 10;

Int * const Pa = &;

Const int * CPA = &;

// Pa = & B; // Error

CPA = & B;

* PA = 5;

// * CPA = 5; // Error

Return 0;

}

Is it easy?

In fact, even so, I think everyone still needs to memorize it, isn't it? It's very troublesome. Maybe I forget it one day... I can teach you how to learn this experience:

In fact, you only need to remember that the constant string is of the const char * type.

For example:

Const char * P = "xinfanyiluan ";

P = "xinfanyiluan2 ";

// * P = 'D'; // error. The constant cannot be assigned.

Because it is a constant string, its value cannot be changed naturally, right?

Very good, so only one const is displayed, isn't it? It's still on the left of *, isn't it?

Now, you can associate const char * with a constant string:

The pointer is variable, but its pointing value is immutable.

The other case is definitely the opposite, isn't it?

I don't know if you think you don't need to memorize it after learning it like this?

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.