C++核心準則ES.105:避免被0除

ES.105: Don't divide by zero
ES.105:避免被0除
Reason(原因)
The result is undefined and probably a crash.
結果無定義,很可能會導致程序崩潰。
Note(注意)
This also applies to?%.
本規(guī)則也適用于取余運算。
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();
}
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
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向對象思考】輕松學習每一天!
面向對象開發(fā),面向對象思考!
評論
圖片
表情
