【发布时间】:2011-02-07 16:27:59
【问题描述】:
有 (1) 个:
// assume x,y are non-negative
if(x > max - y) error;
和(2):
// assume x,y are non-negative
int sum = x + y;
if(sum < x || sum < y) error;
哪个是首选或有更好的方法。
【问题讨论】:
-
实际上,副本根本不是副本,它是在谈论具有明确定义的环绕语义的
unsigned,而溢出有符号整数是C中未定义的行为。 -
sum < x和sum < y都不需要检查。 -
这以前是作为How to detect integer overflow? 的副本关闭的,但这是关于
unsigned,其中包装是明确定义的行为。签名int更难,因为你不能只添加并然后检查它是否溢出,那已经是UB,因此编译器可以假设没有溢出!
标签: c integer-overflow