检查算术运算中的溢出条件 [英] Check for overflow condition in an arithmetic operation

查看:109
本文介绍了检查算术运算中的溢出条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在C / C ++中检测整数溢出的最佳方法

我们如何检查加法,乘法或减法等算术运算是否会导致溢出?

how do we check if any arithmetic operation like addition, multiplication or subtraction could result in an overflow?

推荐答案

首先检查操作数的大小,然后使用 std :: numeric_limits 。例如,对于添加:

Check the size of the operands first, and use std::numeric_limits. For example, for addition:

#include <limits>

unsigned int a, b;  // from somewhere

unsigned int diff = std::numeric_limits<unsigned int>::max() - a;

if (diff < b) { /* error, cannot add a + b */ }

您无法在之后一般可靠地检测算术错误,因此您必须先执行所有检查。

You cannot generally and reliably detect arithmetic errors after the fact, so you have to do all the checking before.

您可以轻松地对此方法进行模板化,使其适用于任何数字类型。

You can easily template this approach to make it work with any numeric type.

这篇关于检查算术运算中的溢出条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆