'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.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容