C++ Pointer Constants, Constant Pointers, and Constant Pointer Constants

Const is short for constant. As long as a variable is decorated with const in front of it, it means that the data in the variable can be accessed and cannot be modified. That is, const means "read-only". Any attempt to modify this variable will result in a compilation error. const is ensured by the compiler performing checks at compile time (that is, variables of const type cannot be changed, which is a compilation error, not a runtime error.) So we can modify the const definition as long as we find a way to fool the compiler. constant, and no error is reported at runtime.
1. Whoever is close to const cannot be modified;
2. Because constants cannot be modified after they are defined, variables must be initialized when using const to define variables.

1. Pointer constants

Pointer constant means that the pointer itself is constant. The address it points to is immutable, but the content of the address can be changed through the pointer. The address it points to will last a lifetime until the end of its lifetime. One thing to note is that pointer constants must be initialized at the same time when they are defined.

int *const p2 = &c; // *在前,定义为指针常量
int main()
{
    
    
	int a = 2;
	int b = 3;
	int *const c = &a;
	printf("albert:%p\n", c);
	c = &b;                     //报错:expression must be a modifiable lvalue	
	printf("albert:%p\n",c);
}
--------------------------------------------------------------------------
int main()
{
    
    
	int a = 2;
	int b = 3;
	int *const c = &a;
	*c = 4;
	printf("albert:%d\n",*c);   //4
}

Second, the constant pointer

A constant pointer refers to a pointer to a constant. As the name implies, the pointer points to a constant, that is, it cannot point to a variable, the content it points cannot be changed, and the content it points cannot be modified through the pointer, but the pointer itself is not a constant, it The value of itself can be changed to point to another constant.

int const *p1 = &b; //const 在前,定义为常量指针
const int  *p1 = &b;
#改变指针b指向地址的内容
int main()
{
    
    
	int a = 2;
	int const *b = &a;
	*b = 3;          //报错:expression must be a modifiable lvalue	
	printf("albert:%d\n",a);
}
----------------------------------------------------------------------------
#改变指针b的指向
int main()
{
    
    
	int a = 2;
	int b = 3;
	int const *c = &a;
	printf("albert:%p\n", c);    
	c = &b;
	printf("albert:%p\n",c);
}

3. Constant pointer constant

const   int * const *p1 = &b;
int const  *const p1 = &b;

Constant pointer Constant pointer cannot be changed, and the value pointed to by the pointer cannot be changed
.

Guess you like

Origin blog.csdn.net/qq_52302919/article/details/123736322