Difference between 'const int*', 'int const*','int* const'

今天写作业被这个const搞得很自闭,因此来总结一下,避免以后踩坑(此处不一定是int,可以是任意type)

const这个东西对于一般变量很简单,const int a and const a int are totally same. Both of them tell the compiler that the value stored in a can not be modified. But when it is combined with pointer, things go complicated

const int *

For C++, int* is not viewed as a type. Only *a be viewed as a mark telling the complier a is a pointer. So as we have already known that int const is same with const int, int const *a is also same with const int *a. Both of them means *a is a const, which means the value poined by a can not be modified but a, as a pointer, can point to different places.

int* const

By contrast, the const in int* const is a mark for a, so a, as a pointer, can only point to one specific place(determined when it is initialized), but the value pointed by it can be changed.

Besides, we can combine two usages of consttogether: const int* const a--a, as a pointer, can not be modified and the value pointed by a cannot be modified.