/* Determine whether argumnts can be substracted without overflow */
int usub_ok(unsigned int x, unsigned int y)
{
return !y || !uadd_ok(x, -y);
}
问题三: 无符号数的乘法越界问题
[定理]
[理解]
等价条件可以相互推导即可.
[url=]复制代码[/url] 代码如下:
/* Determine whether arguments can be multiplied without overflow */
int umul_ok(unsigned int x, unsigned int y)
{
unsigned int p = x * y;
return !x || p/x==y;
}
/* Determine whether arguments can be multiplied without overflow. */
int tmul_ok(int x, int y)
{
#if 0
int p = x * y;
return !x || p/x==y;
#endif
return umul_ok(x, y); /* 直接调用 */
}