const 和 指针

const到底修饰谁?谁才是不变的?

下面是我总结的经验,分享一下。

 

如果const 后面是一个类型,则跳过最近的原子类型,修饰后面的数据。(原子类型是不可再分割的类型,如int, short , char,以及typedef包装后的类型)

 

如果const后面就是一个数据,则直接修饰这个数据。

 1 int main()
 2 {
 3     int a = 1;
 4 
 5     int const *p1 = &a;        //const后面是*p1,实质是数据a,则修饰*p1,通过p1不能修改a的值
 6     const int*p2 =  &a;        //const后面是int类型,则跳过int ,修饰*p2, 效果同上
 7 
 8     int* const p3 = NULL;      //const后面是数据p3。也就是指针p3本身是const .
 9 
10     const int* const p4 = &a;  // 通过p4不能改变a 的值,同时p4本身也是 const
11     int const* const p5 = &a;  //效果同上
12 
13     return 0;
14 
15 }
 1 typedef int* pint_t;  //将 int* 类型 包装为 pint_t,则pint_t 现在是一个完整的原子类型
 2 
 3 int main()
 4 {
 5 
 6     int a  = 1;
 7     const pint_t p1 = &a;  //同样,const跳过类型pint_t,修饰p1,指针p1本身是const
 8     pint_t const p2 = &a;  //const 直接修饰p,同上
 9 
10     return 0;
11 
12 }

 



作者:喜欢编程的狗子
链接:https://zhuanlan.zhihu.com/p/345043534
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2022-01-06 19:40  mcwhirr  阅读(23)  评论(0)    收藏  举报