Const keyword, const
Analyze the following definitions:
const char* p1;char const* p2;char* const p3;const char** p4;char const** p5;char* const* p6;char** const p7;
There are no problems with the first three in 90%. Many people will be confused about the following several estimates. I have checked some materials (including online documents and books ), however, I personally feel that the role of those materials on the const, the const pointer and the pointer to the const value are slightly lacking and slightly messy. Therefore, I wrote this note for the purpose of throwing bricks and jade. You are welcome to give your advice and discuss it.
The role of the const keyword can be summarized as: the first keyword on the rightSymbolLimited to constant. The symbol here is defined:Data Type [*]Or[*] Variable nameOr*(Square brackets indicate optional ). When defining (declaring) a variable, if the variable name is modified to constant, you must assign a value when defining (declaring) the variable. According to the above theory, p1 ~ P7 is the variable name. In char * const p3, const modifies p3, and p3 must be assigned a value when defined; In const char ** p4, const modifies char *, * p4 points to const char *, * p4 does not need to be assigned a value when it is defined. The others are the same.
The second penultimate section on page 19th of Expert C Programming said:
To make the assignment form legal, either of the following conditions must be met: both operands are pointers to compatible types with or without delimiters, the Type pointed to by the Left pointer must have all the qualifiers of the type pointed to by the right pointer.
That is to say, when assigning values, either the two sides have the same limitations and are compatible types, or the left side has more limitations than the right side. Based on the functions of the previous const, we know thatConst char **AndChar **Is an incompatible type and cannot be assigned values to each other.