我正在尝试编写一个累加器,它在给定无约束输入的情况下表现良好。这似乎不是小事,需要一些相当严格的计划。真的这么难吗?

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;
}

编辑:我已经消除了风格偏见

最佳答案

你是否考虑过:

if ( max - *accumulator < amount )
    return 1;

*accumulator += amount;
return 0;

通过在“幼稚”版本中更改第一次比较的方向,可以避免溢出,即查看剩余空间(安全)并将其与要添加的量(也安全)进行比较。
此版本假设在调用函数时,*accumulator永远不会超过max的值;如果要支持这种情况,则必须添加额外的测试。

10-07 23:24