I would like to define some kind of safe division (and modulo) function, one that would return some predefined value when attempting to divide by zero. I don't want to throw exceptions, just to return some "reasonable" value (1? 0?) and continue the program flow. Obviously there is no correct return value, but I wonder if there is some standard or known approach to this
Since you're ask for C++ specifically, you can do
pair< int, bool > safe_div( int lhs, int rhs ) {
if ( rhs == 0 || lhs == INT_MIN && rhs == -1 ) return make_pair(0, false);
else return make_pair( lhs/rhs, true );
}
alternately with boost::optional
optional<int> safe_div( int lhs, int rhs ) {
if ( rhs == 0 || lhs == INT_MIN && rhs == -1 ) return optional<int>();
else return lhs/rhs;
}
I'm assuming you want an integer operation and I added a check for overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With