cbsearch

The compar callback function for bsearch needs only implementation of equality?


From cppreference,

To perform the search, the function performs a series of calls to compar with key as first argument and elements of the array pointed to by base as second argument.

For a given array int arr[] = {1, 2, 3, 4, 5, 6, 7}, searching for the element 6 you need to pass a callback function to bsearch.Does my int compar (const void* pkey, const void* pelem); function needs to be able to return one of the following three cases:

or it suffice to implement the compar function just for equality (e.g return 0 when searched value equals current element)?


Solution

  • Your comparison function must return the correct return value for all possible inputs. Furthermore, the vector must be sorted consistently wirh the comparison function: if the value a comes before b in the vector, then compar(&a, &b) must be less than or equal to 0. bsearch doesn't check that, but if it's not the case, bsearch will probably return the wrong result. Or worse.

    Anyway, it's not possible to implement a function which only sometimes returns a value, if that's what you meant. Unless a function's return value is not used, the function must return something. C does not enforce this requirement, but if you ignore it, your program has Undefined Behaviour, which means that bad things will happen.