const的使用

const的作用:定义常变量,不允许修改其值。

例如:int const p = 10;如果再给p赋值,p = 20,它是error ; int const p1;也是error ;因为它没有初始化。

const的使用如下:

1、基本的数据类型对于const是透明的。

int const ca = 0;   const int cb = 0;ca和cb是等价的。

const放在int的左边和右边都可以,修饰的是ca和cb;

2、const限定它的直接右边。

const放在数据类型之前:const int *cp = &a;int是透明的,看它的时候可以当它不存在,const修饰*cp, 因为它不能再赋值,所以*cp不能做左值;*cp = 100是error;但p = &b是OK。

const放在*之后:int *const cp2 =&a;const修饰cp2,cp2 = &b是error;所以cp2作为直接右边不能做左值,*cp2 = 100是OK。

const放在*之前:int const *cp3 = &a; const修饰*cp3;//cp3等价cp.

3、权限可以缩小或者同等传递,但不能放大。

#include<stdio.h>

int main()
{
    int a = 10;
    int b = 20;
    const int ca = 10;
    const int cb = 10;
    int *p1 = &a;
    //int *p2 = &ca;//error
    const int *p3 = &a;
    const int *p4 = &ca;
    int *const p5 = &a;
    //int *const p6 = &ca;//error
    return 0;

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值