Pointer constants and constant pointers for c++ learning

foreword

In C++, pointer constant (constant pointer) and constant pointer (pointer to constant) are two different types of pointers that have different meanings and uses.

text

Constant pointer:
A pointer constant is a pointer whose memory address cannot be modified. That is, you cannot make it point to a different memory location, but you can change the contents of the memory location pointed to by the pointer.
A pointer constant must be initialized when it is declared, because its pointing will not change.
Pointer constants are declared using the const keyword in front of the pointer type.
Example:

int x = 5;
int y = 10;
const int* ptr = &x; // 声明一个指向常量整数的指针常量
ptr = &y; // 合法,可以改变指向不同的整数,但不能改变指向的整数的值
(*ptr)++; // 不合法,不能修改指向的整数的值

Constant pointer (pointer to constant):
A constant pointer is a pointer, the memory address it points to can be changed, but the content of the pointed memory location cannot be modified through it. That is, you can make it point to different memory locations, but you cannot modify the values ​​of those memory locations through it.
When declaring a constant pointer, use the const keyword in front of the type pointed to by the pointer.
Example:

int x = 5;
int y = 10;
int* const ptr = &x; // 声明一个常量整数指针
(*ptr)++; // 合法,可以修改指向的整数的值
ptr = &y; // 不合法,不能改变指针指向的地址

To summarize the difference:

The pointer constant cannot be changed, but the value of the pointed memory location can be modified.
The pointing of the constant pointer can be changed, but the value of the pointed memory location cannot be modified through it.
According to your needs, choose the appropriate type to declare the pointer to ensure safe and correct operation.

Guess you like

Origin blog.csdn.net/wniuniu_/article/details/132722538
Recommended