you should replace your exit call with a return to be honest, you dont want to terminate the application when this function fails. Instead just return -1 because its very unlikely you are going to find your element at max uint. The calling code knows how big the array is anyway so if max uint is a valid return value the calling code can determine this.
Binary search implementation
How do I choose a failure value in an unsigned int?
Maybe you can return a value higher than the array size (elements+1) and when you call that function always check if the return value is less than elements. It might work if you know you won't have gigant arrays as input. It doesn't sound very intuitive maybe, but if you can't change the return type of the function you'll have setup a convention.
Anyway, it's not THAT werid since some functions that work over collections do a similar thing. Look at std::find, if the value can't be found it returns "last", which is a parameter you must supply to that function instead of a constant error value, then when you call std::find you always do something like:
returnedValue = std::find(array.begin(),array.end(),value);
if ( returnedValue != array.end() )
{
// something
}
Yeah there's two common conventions: for stuff that's based around iterators, the standard idiom is returning 'end' (index of last item + 1, same as size), or the other common idiom is returning an obviously invalid value, such as NULL for pointers, -1 for ints, or max value for unsigned (though it should probably be signed, forcing the user to cast to unsigned, as a reminder that they should also check for -1).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement