Name

bsearch function — Performs a binary search

Synopsis

extern "C"
  void* bsearch(const void* key, const void* base, size_t count, size_t size, int
               (*compare)(const void*, const void*))
extern "C++"
  void* bsearch(const void* key, const void* base, size_t count, size_t size, int
               (*compare)(const void*, const void*))

The bsearch function uses a binary search to search for key in the array base, in which each element takes up size bytes. There are count elements in the array.

The compare function is called with key as the first argument and a pointer into the array as the second. The function should return an integer less than zero if the key is less than the array element, greater than zero if the key is larger, or 0 if the key is the same as the array element.

The bsearch function returns a pointer to the array element that matches key or a null pointer if no element matches.

Two versions of bsearch are declared so the compare function can have "C" linkage or "C++" linkage.

See Also

qsort function, binary_search in <algorithm>

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.