Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe division function

Tags:

c++

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

like image 884
GabiMe Avatar asked Aug 29 '26 07:08

GabiMe


1 Answers

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.

like image 124
Potatoswatter Avatar answered Aug 31 '26 00:08

Potatoswatter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!