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(反面示例)
double divide(int a, int b)
{
// BAD, should be checked (e.g., in a precondition)
return a / b;
}
Example, good(范例)
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
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!
,