A classic question: the difference between the following two statements:
1) const char * P
2) char * const P
The const keyword here is used to modify constants. The book says that const will modify the object closest to it. Therefore, the two statements above mean:
1) P is a pointer to a constant character. It does not change the value of char, that is, the value of this character cannot be changed after initialization during definition.
2) P is a constant pointer to a character. It is the value of P, that is, the pointer cannot point to anything else.
Now I have correctly stated the meaning of the two, But how should I remember them?
At least I think I often forget it, and I may be confused when I encounter it again later. -_-!
Inadvertently, I saw someone on the Internet introducing a good memory method, sharing the following:
Bjarne provides a mnemonic method in his book The C ++ programming language -"
*Divide a statementFrom right to leftRead ".
Note the syntax. * read as pointer to (pointer to...). Const (constant) is an adjective, char (variable type) and P (variable name) are of course nouns.
1) const char * P reading: P is a pointer to a const Char. Translation: P is a pointer (variable) that points to a constant character (const char ).
2) char * const P: P is a const pointer to a char. Translation: P is a constant pointer (const p) that points to a character (variable ).
From the blue marks, we can also see the previous saying that "const modifier leaves the nearest object.
Pay attention to the following situations.
First, let's look at the const int A and INT const A. There is no separator * here. Although the position of const is different, the meaning remains unchanged. It const modifies int and constant integers.
Let's look at the const char * P and char const * P. At first, it is divided by *. Although the position of the const has changed, it is modifying the char and constant characters.
I don't know if you have a deeper understanding of the const statement?