Constant pointer
A constant pointer is a pointer to a constant, and the contents of the memory address pointed to by the pointer are non-modifiable.
Constant pointer defines "const INT *p=&a;" Tells the compiler that *p is a constant and cannot manipulate *p as an lvalue. But the pointer p here is also a variable whose contents hold the address of the constant, so it is permissible to declare the constant pointer again, and the pointer is allowed to be modified, for example:
int a=0,b=1;
const int *p; Declaring a constant pointer p
p=&a; P Point to a
p=&b; Modify the pointer p to point to B, allowing
*p=2; Not allowed
Pointer constants
A pointer constant is a constant of a pointer, which is a pointer to an immutable address, but can be modified by what it points to.
Pointer constants define "int *const p=&a;" Tells the compiler that p is a constant and cannot operate as an lvalue, but allows you to modify what it points to, that is, *p is modifiable. A pointer constant must be initialized at the same time as it is declared, and it is not allowed to declare a pointer constant before assigning it, which is the same as declaring a general constant, for example:
int a=0,b=1;
int *const p2; Not allowed, it must be initialized
p2=&b; Not allowed, p2 is a constant is not allowed as a left value
*p1=2; Allows you to modify the value of the pointer *p1
If the pointer is a function parameter, we often use the pointer constant as a parameter when we do not want the calling function to arbitrarily modify the parameter pointer and just want to modify the content pointed to by the parameter pointer. For example:
There are two shape variables, a, B, we write a function for exchanging a A, a, using pointers as parameters, the function modifies the value of the parameter pointer is what we do not want, then the parameter can be set as a pointer constant, if the function of the pointer to modify the compilation will be an error.
void Exchange (int *const a,int *const b)
{
int temp;
Temp=*a;
*a=*b;
*b=temp
}
In fact, if the function does not modify the value of the parameter itself, we generally add a const qualification to the parameter, which is also a small trick to improve the quality of the code, in the method of the class, if the method does not modify the value of the class property, we often add the method const.
Constant pointer and pointer constant (GO) in C + +