liveBook · Manning

Bsearch

As explained in Modern C, Third Edition

bsearch is the C standard-library function that performs a binary search on a sorted array using a comparison function.

bsearch performs a binary search over a sorted array. It accepts the search key, an untyped array base, the element count, the element size, and a comparison-function pointer. section 11.4

typedef int compare_function(void const*, void const*);

void* bsearch(void const* key, void const* base,
              size_t n, size_t size,
              compare_function* compar);

void qsort(void* base,
           size_t n, size_t size,
           compare_function* compar);

The prototype shows how bsearch combines void pointers, element size, element count, and a comparator to remain type-generic. section 11.4

The comparator receives pointers to elements, casts them to the appropriate type, and returns a negative value when the first precedes the second, zero when they compare equal, or a positive value otherwise. section 11.4

Safe integer comparison

Compare integers with explicit relational tests rather than returning *a - *b: subtraction can overflow when the operands are far apart.

How Modern C, Third Edition covers it

How deep it goes
Explains the interface, erased array types, element sizing, and comparator contract without descending into search-loop internals.
Examples
Uses unsigned comparison code and contrasts safe relational comparison with overflow-prone integer subtraction.
What it assumes
Assumes familiarity with arrays, pointers, casts, and function pointers while defining the comparator protocol explicitly.
What you can do after
Apply it via the C standard library with correctly sized elements and a consistent comparator.
How it connects
Connects bsearch to function pointers, void pointers, comparison functions, and qsort.

Also explained in

Compare how 2 books explain bsearch →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.