[c++] const pointer
Reference : "C++ from entry to mastery" People's Posts and Telecommunications Publishing House
The quantity represented by const is a constant. Can the data of the pointer type also use const?
of course can. The keyword const can be used before or after a pointer type. A const pointer has the following two forms:
const int *p1 =&a; //Pointer to an integer constant whose value cannot be changed
int* const p2 =&b; //Pointer to an integer constant whose address cannot be changed
Among them, p1 is a pointer to an integer constant, and the value it points to (*p1) cannot be changed, but the address it points to and the value of the variable (the value of a) can be changed; p2 points to a pointer to an integer constant, which points to The address (&b) cannot be changed, but the value it points to (*p2) can be changed.
Here's a programming example:
original:
#include<iostream> using namespacestd; intmain() { int a=1,b=2,c=3; const int *p1; //correct int* const p2; // will report an error! ! ! Uninitialized p1=&a; p2=&b; //Error! The address pointed to by p2 cannot be changed cout<<"*p1:"<<*p1<<endl; cout<<"*p2:"<<*p2<<endl; return 0; }
Among them, int* const p2; // uninitialized, an error will be reported. This is because the address pointed to by p2 cannot be changed, so it needs to be initialized.
After modification:
int* constp2=&b; //Initialization, via
Modify again:
int* constp2=&b; //Initialization, via p2=&c; //error
The second sentence will report an error because the address pointed to by p2 cannot be changed, it can only point to b, and cannot point to other variables (addresses). But you can change the value pointed to by *p2, as follows:
*p2=3; //correct
After modification:
const int *p1; //Pointer to an integer constant, the integer pointed to cannot be changed p1=&a; *p1=5; //Add
Among them, *p1=5 will report an error, because p1 is a pointer to an integer constant and the value it points to cannot be changed .
Modify again:
const int *p1; //Pointer to an integer constant, the integer pointed to cannot be changed p1=&a; //*p1=5; //Error will be reported a=5; //Add, pass
Among them, *p1=5 will report an error, and a=5 will pass, because the value pointed to by p1 cannot be changed, but the value of variable a can be changed directly .
Overall comparison:
p1=&c; //Correct, p1 can change the address pointed to
p2=&c; //Error, p2 cannot change the address pointed to
*p1=10; //Error, the value pointed to by p1 cannot be changed
*p2=10; //Correct, the value pointed to by p2 can be changed
so:
const int *p1 =&a; //The value pointed to by p1 cannot be changed, but the address pointed to is variable
int* const p2 =&b; //The address pointed to by p2 cannot be changed, but the value it points to can be changed
------------------------------------------- END -------------------------------------