15

When browsing through a draft of the standard (N4527), I found the following paragraph ([alg.c.library]):

The function signature:

bsearch(const void *, const void *, size_t, size_t,
    int (*)(const void *, const void *));

is replaced by the two declarations:

extern "C" void* bsearch(const void* key, const void* base,
                         size_t nmemb, size_t size,
                         int (*compar)(const void*, const void*));
extern "C++" void* bsearch(const void* key, const void* base,
                           size_t nmemb, size_t size,
                           int (*compar)(const void*, const void*));

And the same stuff for qsort.

I also found in [dcl.link]:

If two declarations declare functions with the same name and parameter-type-list (8.3.5) to be members of the same namespace or declare objects with the same name to be members of the same namespace and the declarations give the names different language linkages, the program is ill-formed;

What is the purpose of these two extern declaration of the same function? Why is this block not ill-formed?

Holt
  • 36,600
  • 7
  • 92
  • 139
  • Which Standard are you targeting? Seems to have changed, because if I understand [`[extern.names]/4`](http://eel.is/c++draft/extern.names#4) correctly, it is implementation defined if those functions are marked `extern`. – Rakete1111 Jul 15 '17 at 20:07
  • @Rakete1111 N4527 – Holt Jul 15 '17 at 20:07

1 Answers1

16

The parameter type lists are not the same. Really. I'm not kidding. The two compar arguments have different types: in the first declaration, because the function is extern "C", the compar function is also extern "C"; in the second one, the compar function is extern C++". And that's why there are two declarations: so that you can call bsearch with functions with either language linkage.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165