【发布时间】:2014-08-19 22:17:45
【问题描述】:
我正在尝试编写一个在输入不受约束的情况下表现良好的累加器。这似乎不是微不足道的,需要一些非常严格的计划。真的有这么难吗?
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;
}
编辑:我已经消除了风格偏见
【问题讨论】:
-
“复杂”版本比“简单”版本多 1 行代码(如果您对 safe 使用与 naive 相同的样式约定),这似乎并不太“难”...
-
如果累计值和最大值之间的差值大于新值,则抛出异常(或其他)。
-
A) 为什么不通过引用而不是使用指针来传递?和 B) 为什么不使用 or (
||) 并利用短路使safe_accumulator与naive_accumulator的行数相同? -
@Jongware:好吧,除非
unsigned int和unsigned long的宽度相同。 -
@Jongware 除非 unsigned long 与 unsigned int 的大小相同。
标签: c++ c undefined-behavior integer-overflow