const int *p、int *const p、const int* const p的区别

一、首先

const int p = 10;
int const p = 10; //是没有区别的

二、const int *p的用法

#include <stdlib.h>  
#include <stdio.h>  
#include <string.h>  

int main(int argc, char **argv)  
{  
    int a = 1;  
    int b = 2;  
    const int *p;  

    p = &a;  
    p = &b;  
    b = 3;  
    //*p = 4;     error: assignment of read-only location ‘*pprintf("%d\n", *p);  

    return 0;  
}  
//结果
3

Process returned 0 (0x0)   execution time : 0.507 s
Press any key to continue.
//说明
*p是常量,不可更改,但指针p还是变量,你想怎么 变都可以。

三、int *const p的用法

#include <stdlib.h>  
#include <stdio.h>  
#include <string.h>  

int main(int argc, char **argv)  
{  
    int a = 1;  
    int b = 2;  
    int *const p = &a;  //只能在声明的时候就给它赋初值,否则还是会报错的  

    //p = &b;           error: assignment of read-only location ‘*p’  
    a = 3;  
    printf("%d\n", *p);  

    return 0;  
} 
//结果
3

Process returned 0 (0x0)   execution time : 0.233 s
Press any key to continue.
//说明
p是常量,也就是说p所指向的地址是不可以更改的,所以当把b的地址赋值给p时就会报错!但是p所指的地址内容是可以改变的。

四、const int *const p

#include <stdlib.h>  
#include <stdio.h>  
#include <string.h>  

int main(int argc, char **argv)  
{  
    int a = 1;  
    int b = 2;  
    const int *const p = &a;  

    //p = &b;  
    //*p = 3;  
    printf("%d\n", *p);  

    return 0;  
}  
//说明
这个就相当于以上两种情况的混合体,p是常量,所以不能把b的地址赋给p;同时*p也是常量,所以*p的内容不可更改!

五、总结

根据const的位置,先确定哪个是常量。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值