C++ primer plus (第六版)第七章arrfun4.cpp代码及解释

如有失误之处,还恳请指教!!!

// arrfun4.cpp -- functions with an array range
#include <iostream>
const int ArSize = 8;
//函数原型:返回值int类型,含有两个参数,两个参数均为指针
int sum_arr(const int *begin, const int *end);
int main()
{
    using namespace std;
    int cookies[ArSize] = {1, 2, 4, 8, 16, 32, 64, 128};
    //  some systems require preceding int with static to
    //  enable array initialization
    //该函数具有两个参数,两个参数分别表示数组首元素地址和数组尾元素地址
    int sum = sum_arr(cookies, cookies + ArSize);
    cout << "Total cookies eaten: " << sum << endl;
    //该函数具有两个参数,两个参数分别表示数组首元素的地址,和数组第四个元素的地址
    sum = sum_arr(cookies, cookies + 3); // first 3 elements
    cout << "First three eaters ate " << sum << " cookies.\n";
    //该被调用函数含有两个参数,一个表示数组第5个元素的地址,一个表示数组前9个元素的地址
    sum = sum_arr(cookies + 4, cookies + 8); // last 4 elements
    cout << "Last four eaters ate " << sum << " cookies.\n";
    // cin.get();
    return 0;
}

// return the sum of an integer array
//函数定义:因为该函数以指针作为形式参数,因此被调用函数应当以地址作为实际参数
int sum_arr(const int *begin, const int *end)
{
    const int *pt;
    int total = 0;

    for (pt = begin; pt != end; pt++)
        total = total + *pt;
    return total;
}

猜你喜欢

转载自blog.csdn.net/weixin_38401090/article/details/86562420