指针和const

我们都知道C++中数组名实际上是数组头指针,在函数中我们不希望改变数组中元素的值,但是由于疏忽却有可能无意中改变

下面这样的做法可以一定程度上避免这种情况

#include<iostream>
using namespace std;
const int ArSize = 8;
int sum_arr(const int * begin,const int * end);

int main(){
    int cookies[ArSize] = {1,2,4,8,16,32,64,128};
    cout<<"sum:"<<sum_arr(cookies,cookies+ArSize);
    cout<<"first 3:"<<sum_arr(cookies,cookies+3);
    cout<<"last 4:"<<sum_arr(cookies+4,cookies+8);
    return 0;
}

int sum_arr(const int * begin,const int * end){
    const int * pt;
    int total = 0;
    for(pt = begin;pt!=end;pt++){
        total+=*pt;
    }
    return total;
}

在函数原型与函数声明的参数列表的类型前加上const关键字,就可以避免修改例如 *begin指向的值,但是我们依然能够修改begin的值

比如下面就修改了begin的值(const 类型 * 类似声明是避免修改指针指向的值,而不是指针的值)

int sum_arr(const int * begin,const int * end){
    const int * pt;
    int total = 0;
    begin++;
    for(pt = begin;pt!=end;pt++){
        total+=*pt;
    }
    return total;
}

下面这样就能够避免修改指针的值

int sum_arr(int * const begin,const int * end);//原型也做对应修改

int sum_arr(int * const begin,const int * end){
    const int * pt;
    int total = 0;
    //begin++; 此时如果执行此操作将会报错
    for(pt = begin;pt!=end;pt++){
        total+=*pt;
    }
    return total;
}

给出总结

1.const 类型 * 名字 意为:一个指向常量的指针

2.类型 * const 名字 意味:指向某种类型的常量指针

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值