Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling qsort with a pointer to a c++ function

Tags:

c++

I have found a book that states that if you want to use a function from the C standard library which takes a function pointer as an argument (for example qsort), the function of which you want to pass the function pointer needs to be a C function and therefore declared as extern "C".

e.g.

extern "C" {
  int foo(void const* a, void const* b) {...}
}

... 
qsort(some_array, some_num, some_size, &foo);

I would not be surprised if this is just wrong information, however - I'm not sure, so: is this correct?

like image 851
DaVinci Avatar asked Sep 21 '26 12:09

DaVinci


1 Answers

A lot depends on whether you're interested in a practical answer for the compiler you're using right now, or whether you care about a theoretical answer that covers all possible conforming implementations of C++. In theory it's necessary. In reality, you can usually get by without it.

The real question is whether your compiler uses a different calling convention for calling a global C++ function than when calling a C function. Most compilers use the same calling convention either way, so the call will work without the extern "C" declaration.

The standard doesn't guarantee that though, so in theory there could be a compiler that used different calling conventions for the two. At least offhand, I don't know of a compiler like that, but given the number of compilers around, it wouldn't surprise me terribly if there was one that I don't know about.

OTOH, it does raise another question: if you're using C++, why are you using qsort at all? In C++, std::sort is almost always preferable -- easier to use and usually faster as well.

like image 176
Jerry Coffin Avatar answered Sep 23 '26 02:09

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!