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.
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
beginandendparameters):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.