[C&C++ record learning] pointer and const

There are three cases of const modified pointer

  1. const modified pointer --- constant pointer

  2. const modified constant --- pointer constant

  3. const modifies pointers and modifies constants

1. const modified pointer --- constant pointer

const modifies the pointer, the pointer point can be changed, and the value pointed to by the pointer cannot be changed

int a = 10;
int b = 10;
		

//const修饰的是指针,指针指向可以改,指针指向的值不可以更改
const int * p1 = &a;
p1 = &b; //正确
// *p1 = 100; // 报错

int const * a; //同上

p1 is a pointer to a const object of type int, called a constant pointer.

Note: const ( constant ) int * ( pointer ) p. const is followed by *, so *p cannot be modified, but p can be modified.

2. const modified constant --- pointer constant

const modifies a constant, the pointer point cannot be changed, and the value pointed to by the pointer can be changed

int a = 10;
int b = 10;


//const修饰的是常量,指针指向不可以改,指针指向的值可以更改
int * const p2 = &a;
//p2 = &b; //错误
*p2 = 100; //正确

As the name suggests, a pointer constant is a constant, but it is modified by a pointer.

Note: int * ( pointer ) const ( constant ) p2. const is followed by p2, so p2 cannot be modified, while *p2 can be modified.

3. const modifies pointers and constants

int a = 10;
int b = 10;


//const既修饰指针又修饰常量
const int * const p3 = &a;
//p3 = &b; //错误
//*p3 = 100; //错误

p3 is a const pointer, and then points to a const object of type int. It is called a constant pointer to a constant.

Guess you like

Origin blog.csdn.net/Zhouzi_heng/article/details/112340636