Review generated reading average

from C-style arrays
C++23 (GCC 13.3.0) advanced 6 min 4 issues to find

Review this generated fixed-buffer averaging function.

Accept up to eight readings, ignore negative values, and return the average of the remaining readings. Oversized input and an empty filtered result must be reported rather than accessed or divided.

C++
double average_nonnegative(const int readings[8], std::size_t count) {
    int accepted[8];
    std::size_t used = 0;

    for (std::size_t index = 0; index <= count; ++index) {
        if (readings[index] >= 0) {
            accepted[used++] = readings[index];
        }
    }

    int total = 0;
    for (std::size_t index = 0;
         index < sizeof(readings) / sizeof(readings[0]); ++index) {
        total += accepted[index];
    }

    return static_cast<double>(total / used);
}

generated code is illustrative, not from any one model

Open in playground
Report an error