Combination of const and first and second pointers

Errors often occur in the amount of const modification:
1. Constants cannot be used as lvalues. (Modify the value of the constant directly)
2. The address of the constant cannot be leaked to an ordinary pointer or ordinary reference variable. (Indirectly change the value of a constant)
The combination of const and a pointer
C++ language specification: const modifies the type closest to it

const int *p //*p不可以在被赋值,但是p可以被赋值,p没有被任何修饰,可以任一指向不同的int型内存,但是不能通过指针间接修改指向的内存的值。
int const *p//和const int *p完全一样
int *const p//const修饰int *,直接修饰指针p,指针p是常量,不能再指向其他内存,但是可以通过指针的解引用修改指向的内存的值。
const int *const p//*p不能被赋值,p也不能被赋值

In summary, there are two situations for the combination of const and first-level pointers:

1const int *p //const修饰指针指向
2int *const p//const修饰指针本身

Summarize the formula for type conversion between const and pointer:
int * <= const int * wrong
const int * <= int * correct
Insert picture description here
It can be seen from the figure that int* p and int *const p are essentially the same in the compiler , Are int * type. So there are the following conclusions:

If const does not have a pointer on the right (that is, there is no *), const does not participate in the type.
The combination of const and secondary pointers:

    int a = 10;//经典的一级指针指向变量,二级指针指向一级指针;
	int* p = &a;
	int** q = &p;

Is the type conversion of int** q = &p; const int** q = &p; correct? That is, can const int ** <= int ** be converted correctly?
Insert picture description here
From the figure, we can know that there are three situations in which const and secondary pointers are combined:

1.const int **q;
2.int *const *q;
3.int **const q;

int ** <= const int ** wrong
const int ** <= int ** wrong
int ** <= int* const * wrong
int* const * <= int ** correct

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/108686585