Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array pointers [] or ++

lets say I want to iterate through an array of doubles and sum them. I have two ways to do this.

A)

double sum (double * series, int size) {
    double sum = 0.0;
    for (int i = 0; i < size; i++) {
        sum += *series++;
    }
    return sum;
}

B)

double sum (double * series, int size) {
    double sum = 0.0;
    for (int i = 0; i < size; i++) {
        sum += series[i];
    }
    return sum;
}

which is better and why / when should I use one over the other.

like image 753
Patrick Lorio Avatar asked Feb 25 '12 18:02

Patrick Lorio


2 Answers

This is a question of readability, it should not affect performance. I think B is the most readable, and therefore preferable.

I could also propose a third variant, which is range-based (note the begin and end parameters):

double sum (double* begin, double* end) {
    double sum = 0.;
    for (double* it = begin; it != end; ++it) {
        sum += *it;
    }
    return sum;
}

This is idiomatic C++ in many cases and generalizes more easily. That is not to say that it is always preferable, it is just another variant in a question about readability and maintainability.

like image 136
Magnus Hoff Avatar answered Oct 14 '22 10:10

Magnus Hoff


I would chose style B as well, but then you should prefer standard algorithms over explicit loops:

#include <numeric>

double sum(const double* const series, const int size) {
    return std::accumulate(series, series + size, 0.0);
}
like image 33
Philipp Avatar answered Oct 14 '22 11:10

Philipp