关键字const用于指针!

声明为const的变量,可确保变量的取值在整个生命周期内都固定为初始化值

const指针有种:

First:指针指向的数据为常量,不能修改,但可以修改指针包含的地址,既指针可以指向其他地方。

1 int HoursInDay = 24;
2 const int* pInteger = &HoursInDay;//cannot use pInteger to change HoursInday
3 int MothsInYear = 12;
4 pInteger = &MonthsInYear;//OK
5 *pInteger = 13;//fail:cannot change data
6 int* pAnotherPointerToInt = pInteger; //fails:cannot assign const to non-const
Second:指针包含的地址是常量,不能修改,但可以修改指针指向的数据。
1 int DaysInMoth = 30;2 int* const pDaysInMoth = &DayInMoth;
3 *pDaysInMoth = 31;//OK
4 int DaysInLunarMonth = 28;
5 pDayInMoth = &DaysInLunarMonth;//fails:Cannot change address!

 

Third:指针包含的地址以及它指向的值都是常量,不能修改。
1 int HoursInDay = 24;
2 const int* const pHoursInDay = &HoursInDay;
3 *pHoursInDay = 25;//fails:cannot change pointed value
4 int DaysInMonth = 30;
5 pHoursInDay  = &DaysInMonth;//fails: cannot change pointer value

 

讲指针传递给函数时,这些形式的const很有用。函数参数应声明为最严格的const指针,以确保函数不会修改该指针指向的值,让函数更容易维护。

转载于:https://www.cnblogs.com/Rainingday/p/5943811.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值