C++核心准则ES.104:防止下溢

2020-06-17 19:12:56 浏览数 (1)

ES.104: Don't underflow

ES.104:防止下溢

Reason(原因)

Decrementing a value beyond a minimum value can lead to memory corruption and undefined behavior.

减少一个值越过最小值,可以引起内存破坏和无定义行为。

Example, bad(反面示例)

代码语言:javascript复制
int a[10];
a[-2] = 7;   // bad

int n = 101;
while (n--)
    a[n - 1] = 9;   // bad (twice)
Exception(例外)

Use unsigned types if you really want modulo arithmetic.

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

Enforcement(实施建议)

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es104-dont-underflow

0 人点赞