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
You can return the value as an output parameter. The function return type could be bool and you return true on success and false on division by zero. Then you simply check for true after the function. But the modern approach is to throw exception instead and catch it in your client code. Then you can choose to ignore it if you want.
The IEEE floating point standard defines what to get from a division by zero.
- +a / +0 gives +Inf
- +a / -0 gives -Inf
- 0 / 0 gives NaN
If you work with integers, you can use this standard to define your own routine, but you have to define what is Inf and what is NaN in integer logic.
i'm assuming this is for ints as ieee floats already fix this
the trouble is what value might be 'reasonable' depends on use so you will need to pass it in e.g.
DivOrDefault(int a, int b, int def)
{
if (b == 0) return def;
return a/b;
}
alternatively you can signal inf/Nan either in band (you could wrap the int in a struct which also has a bool for inf and or nan ) or out of band (as m_pGaldiator suggested)
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.