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:
- return < 0
- return > 0
- return 0
or it suffice to implement the compar function just for equality (e.g return 0 when searched value equals current element)?
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
acomes beforebin the vector, thencompar(&a, &b)must be less than or equal to 0.bsearchdoesn't check that, but if it's not the case,bsearchwill 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.