请问以下四种定义常量指针方法的区别,我已经被绕晕了

const int *p = &a;
int const *p = &a;
int *const p = &a;
const int *const p = &a;
阅读 4.3k
3 个回答

const int*int const*是同一种类型,指针指向的是一个const int,也就是说不能通过指针p来修改a的值。
int* const p=&aconst直接修饰p,即指针本身是const,它的值已经初始化为&a,不能修改,但是可以通过p来修改a的值,如*p=0;
const int* const则是上面二者的叠加,一方面指针p本身是const,其值初始化为&a不能修改,另一方面指针p所指向的数据类型是const int,即不能通过p来修改a的值。

一句话,从右往左读。因为中英文在这里语序相反,所以比较麻烦。

cconst int *p = &a;    // p指针指向const int (p is a pointer to const int)
int const *p = &a;    // p指针指向const int (p is a pointer to const int)
int *const p = &a;    // p为const指针,指向int (p is a const pointer to int)
const int *const p = &a;    // p为const指针,指向const int (p is a const pointer to const int)

此外还有

int *&p;    // p是引用,其被引用对象为指向int的指针 (p is a reference to pointer to int)
int const *& p;    // p是引用,其被引用对象是指向int的指针常量

甚至

int * const * const * * p; // p是指向指向指向指向指向整数的指针常量的指针常量的指针的指针
       // (p is a pointer to a pointer to a const pointer to a const pointer to int)

当然这样就没啥用处了 :P

const就是代表不能修改值,对于 int *p的定义,有两种可能的修改,一个是p指向的内存的值,一个是p的值;
要记住很简单,const离谁近,就谁不能修改;const int *p,离*比离p近,所以*不能修改,即内存的值不可修改;
int * const p;已经跨过*,离p近了,p不可修改,即p这个指向一个地址了,就不能再想指向另一个地址了;

推荐问题