常量指针 指针常量 常量指针指常量 int const * const p const int const * p int* const p int const * p

前言

很容易弄混,记一下好了

总结

  • int const * p等价于 const int *p 都是正常指针指向常量,可以修改指针(指向),不能修改指向的东西的值(指向的东西是const)
  • int* const p 首先是const p 常量的指针,所以指向不能修改,但是指向的东西是可以改的
  • int const * const p ==const int const * p 指针是常量 指向的也是常量 指针本身不能修改,指向的东西也不能修改
  1. 首先很推荐左边的写法,就是后置const,原来我不理解,后面发现标准库里都是这么写的,现在理解了,确实该这么写,因为类型很明确
  2. 按照左边的写法,*右侧的const(p左侧最近的const)限制的是p的类型 *左侧的const则限制的是指向的东西是否const.很清晰呢!

实验代码

int main( int argc, const char** argv )
{
    int normalInt1 = 1;
    int normalInt2 = 2;

    //无修饰指针(p) 指向的类型是 常量的整型(int const)
    int const* p_ci = &normalInt1;
    //修改指针 √
    p_ci = &normalInt2;
    //修改指针指向的值 ×
    // ( *p_ci )             = 3;  // Read-only variable is not assignable

    //常量的指针(const p) 指向的类型是 正常的整形(int)
    int* const cp_i = &normalInt1;
    //修改指针 ×
    // cp_i = &normalInt2;  // Cannot assign to variable 'cpi' with const-qualified type 'int *const'
    //修改指针指向的值 √
    ( *cp_i ) = 3;

    //常量的指针(const p)  指向的类型是 常量的数值(const int).
    int const* const cp_ci = &normalInt1;
    //修改指针 ×
    // cp_ci = &normalInt2;  // Cannot assign to variable 'cp_ci' with const-qualified type 'const int *const'
    //修改指针指向的值 ×
    // ( *cp_ci ) = 3;  // Read-only variable is not assignable

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值