The difference between const char *, char const *, and char * const is almost the same as that in each c ++ interview.
In fact, everyone has this concept, but the three declaration methods are very similar and easy to remember.
Bjarne provides a mnemonic method in his c ++ programming language:
Read a statement from the right to the left.
Char * const CP; (* read as pointer)
CP is a const pointer to Char
Const char * P;
P is a pointer to const char;
Char const * P;
Similar to C ++, because the const * operator does not exist in C ++, const can only belong to the previous type.
The C ++ standard stipulates that the const keyword is equivalent before the type or variable name.
Compatibility of char ** P and const char ** P types
1. Problem
Char * P1; const * P2 = p1; // valid
Char ** P1; const char ** P2 = p1; // invalid. Warning: initialization from incompatible pointer type
Char ** P1; char const ** P2 = p1; // invalid. Warning: initialization from incompatible pointer type
Char ** P1; char * const * P2 = p1; // valid
2. Judgment Rules
Define the object modified by const! For pointers P1, and P2,To enable P2 = p1, read:
"P1 refers to the X-type pointer, and P2 refers to the X-type pointer with const limitation".
Char * P1; const char * P2 = p1; // valid: P1 is a pointer to the (char) type, and P2 is a pointer to a (char) with a const limitation) type pointer.
Char ** P1; const char ** P2 = p1; // invalid: P1 is a pointer to the (char *) type, P2 is a pointer to (const char )*) type pointer.
Char ** P1; char const ** P2 = p1; // invalid; equivalent to upper.
Char ** P1; char * const * P2 = p1; // valid: P1 is a pointer to the (char *) type, p2 is a pointer to the (char *) type with a const limitation.
Last example:
#include <stdio.h>int main(void){ int v1 = 1; int v2 = 2; int const *a = &v1; *a = 2; int *const b = &v2; b = &v1; char**p1; char*const*p2=p1; *p2 = &v1; return 0;}
The following error occurs during compilation:
Const. C: In function 'main ':
Const. C: 9: Error: Assignment of read-only location '*'
Const. C: 12: Error: Assignment of read-only variable 'B'
Const. C: 16: Error: Assignment of read-only location '* p2'