C++进阶:新人易入的那些坑 --1.常量、常指针和指针常量

/*
why use const
a)Guards against inadvertent write to the variable
b)Self documenting
c)Enables compiler to do more optimization,making code tighter,faster
d)const means the variable can be put in ROM
*/
//const 
// A compile time constraint that an object can not  be modified

int main()
{
    const int i = 9;
    //i = 7; wrong
    //如何修改i的值呢?
    const_cast<int&>(i) = 7;

    int j;
    static_cast<const int&>(j) = 7;//wrong,此时j被转成const

    const int *p1 = &i;//data is const,pointer is not
    p1++;
    int * const p2;//pointer is const,data is not
    const int* const p3;//data and pointer are both const

    int const *p4 = &i;
    const int *p4 = &i;
    //If const is on the left of *,data is const
    //If const is on the right of *,pointer is const
}

声明:以上内容B站/Youtube学习笔记,https://www.youtube.com/user/BoQianTheProgrammer/ Advanced C++.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值