Expressions and statements
ES.105
Don't divide by integer zero
Reason
The result is undefined and probably a crash.
Note
This also applies to %.
Example, bad
int divide(int a, int b)
{
// BAD, should be checked (e.g., in a precondition)
return a / b;
}
Example, good
int 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(double a, double b)
{
// good, address via using double instead
return a / b;
}
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