C++中怎么防止溢出​

发布时间:2021-07-06 17:16:04 作者:Leah
来源:亿速云 阅读:332

这篇文章将为大家详细讲解有关C++中怎么防止溢出,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

Reason(原因)

Overflow usually makes your numeric algorithm meaningless. Incrementing a value beyond a maximum value can lead to memory corruption and undefined behavior.

溢出通常会导致数字算法失去意义。超过最大值的增量运算会导致内存破坏和无定义的行为。

Example, bad(反面示例)

int a[10];
a[10] = 7;   // bad

int n = 0;
while (n++ < 10)
   a[n - 1] = 9; // bad (twice)
Example, bad(反面示例)
int n = numeric_limits<int>::max();
int m = n + 1;   // bad
Example, bad(反面示例)
int area(int h, int w) { return h * w; }

auto a = area(10'000'000, 100'000'000);   // bad
Exception(例外)

Use unsigned types if you really want modulo arithmetic.

如果你确实需要按模运算可以使用无符号类型。

Alternative: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.

可选项:对于可以承受一定额外开销的敏感应用,使用带有范围检查的整数或者浮点数。

关于C++中怎么防止溢出就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. C++ 防止重定义
  2. byte转化为Bitmap,防止内存溢出

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++中怎么避免无名枚举

下一篇:C++中怎么防止下溢

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》