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 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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With