Pointer constants and constant pointers
- A pointer constant is a defined pointer that can only be initialized at the time of definition and cannot be changed later. The format is as follows: [data type] [*] [const] [pointer constant name ];
Example:
| 1 |
Char*ConstP1; |
| 2 |
Int*ConstP2; |
Const is located on the right of the pointer Declaration "*", which indicates that the declared object is a constant, and the object data type is a pointer. Therefore, the first sentence defines a read-only integer pointer P1, and the second sentence defines a read-only integer pointer P2. The value of a regular pointer cannot be changed, but the content it points to can be changed. For example:
#include<iostream>using namespace std;int main(){ char a[5]="abcd"; char b[5]="efgh"; char * const p1=a; char * const p2=b; cout<<"Before Change:"<<endl; cout<<"a:"<<a<<endl<<"b:"<<b<<endl; *p1='1'; b[0]='2'; //p1=p2; cout<<"After Changed:"<<endl; cout<<"a:"<<a<<endl<<"b:"<<b<<endl; getchar(); return 0;}Output result:
If the comment is removed, a compilation error occurs: Error c3892: "p1": the constant cannot be assigned (VS 2005 );
The memory address pointed to by the pointer cannot be changed. The pointer value can only be initialized at the time of definition, and cannot be changed elsewhere.
2. A constant pointer is a pointer to a constant. Because the constant Pointer Points to a constant, the value of this object cannot be changed. The format is as follows:
[Data type] [const] [*] [constant pointer name ];
Or
[Const] [data type] [*] [constant pointer name ];
For example:
#include<iostream>using namespace std;int main(){ char a[5]="abcd"; char b[5]="efgh"; const char * p1=a; const char * p2=b; cout<<"Before Change:"<<endl; cout<<"a:"<<a<<endl<<"b:"<<b<<endl<<"p1:"<<p1<<endl; a[0]='1'; p1=p2; //*p2='2'; cout<<"After Changed:"<<endl; cout<<"a:"<<a<<endl<<"b:"<<b<<endl<<"p1:"<<p1<<endl; getchar(); return 0;}Output result:
If the comment is removed, the compilation error is: Error c3892: "p2": the constant cannot be assigned;
It can be seen that the value of the object to which the constant Pointer Points cannot be changed through the constant pointer. This feature is often used to pass function parameters.