Is a safe accumulator really this complicated?

Posted by Martin on Stack Overflow See other posts from Stack Overflow or by Martin
Published on 2014-08-19T22:17:45Z Indexed on 2014/08/19 22:20 UTC
Read the original article Hit count: 172

I'm trying to write an accumulator that is well behaved given unconstrained inputs. This seems to not be trivial and requires some pretty strict planning. Is it really this hard?

int naive_accumulator(unsigned int max,
                      unsigned int *accumulator,
                      unsigned int amount) {
    if(*accumulator + amount >= max) return 1; // could overflow
    *accumulator += max; // could overflow
    return 0;
}

int safe_accumulator(unsigned int max,
                     unsigned int *accumulator,
                     unsigned int amount) {
    // if amount >= max, then certainly *accumulator + amount >= max
    if(amount >= max) {
        return 1;
    }

    // based on the comparison above, max - amount is defined
    // but *accumulator + amount might not be
    if(*accumulator >= max - amount) {
        return 1;
    }

    // based on the comparison above, *accumulator + amount is defined
    // and *accumulator + amount < max
    *accumulator += amount;

    return 0;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about c