C++核心准则ES.105:避免被0除

2020-06-19 17:20:26 浏览数 (2)

ES.105: Don't divide by zero

ES.105:避免被0除

Reason(原因)

The result is undefined and probably a crash.

结果无定义,很可能会导致程序崩溃。

Note(注意)

This also applies to %.

本规则也适用于取余运算。

Example, bad(反面示例)

代码语言:javascript复制
double divide(int a, int b)
{
    // BAD, should be checked (e.g., in a precondition)
    return a / b;
}
Example, good(范例)
代码语言:javascript复制
double divide(int a, int b)
{
    // good, address via precondition (and replace with contracts once C   gets them)
    Expects(b != 0);
    return a / b;
}

double divide(int a, int b)
{
    // good, address via check
    return b ? a / b : quiet_NaN<double>();
}

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

可选项:对于能够承受一定代价的要求严格的应用,可以考虑使用带有范围检查的整数或者浮点数。

Enforcement(实施建议)

  • Flag division by an integral value that could be zero
  • 标记可能为零的整数除数。

原文链接 https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es105-dont-divide-by-zero

0 人点赞