C++中怎么防止溢出​

这篇文章将为大家详细讲解有关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++中怎么防止溢出就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。