Comparison functions for qsort() and bsearch()

Chip Salzenberg chip at tct.uucp
Tue Dec 25 04:54:37 AEST 1990


[This discussion is relevant to both the C and C++ languages; hence
 the cross-post.  Please direct followups appropriately.]

According to rfg at NCD.COM (Ron Guilmette):
>Both qsort() and bsearch() have a similar need to be fed a pointer to a
>function which itself takes two parameters of type pointer-to-T, where
>the type T is the same for both of the two parameters (but is never
>actually the type `void').

Bzzt.  Thanks for playing, though.

Both qsort() and bsearch() require a pointer to a function which does
*actually* take two parameters of type pointer-to-void.  The fact that
the function in question will almost immediately cast those pointers
into pointer-to-T is utterly irrelevant.

Remember that qsort() cannot know the real type of the objects it is
sorting.  Remember also (as noted in an unquoted portion of Ron's
article) that on word-addressed machines, pointer-to-T and
pointer-to-void may differ in representation and/or size.  It is
therefore obvious that qsort() is unable to make a correct call to a
function that has pointer parameters of any type other than
pointer-to-void (or, equivalently, pointer-to-char).

If you declare a comparison function that take parameters of type
pointer-to-T, and pass the address of that function to qsort(), and
qsort() still works, you're quite fortunate (or unfortunate, depending
on how you look at it).  But that doesn't change the fact that such a
practice is not, nor can it ever be, portable.

>But what if that compare routine is stashed away in a precompiled library?

Then the person who wrote it doesn't know what he's doing, and you
should stop using his code immediately.

>In short, IT IS IMPOSSIBLE TO WRITE QSORT() ENTIRELY IN ANSI C OR IN C++
>IN SUCH A WAY THAT IT IS COMPLETELY PORTABLE.

This statement is false.  It is entirely possible to do so, thanks to
ANSI's guarantee that pointer-to-char and pointer-to-void will always
have identical representations.
-- 
Chip Salzenberg at Teltronics/TCT     <chip at tct.uucp>, <uunet!pdn!tct!chip>
"Please don't send me any more of yer scandalous email, Mr. Salzenberg..."
		-- Bruce Becker



More information about the Comp.lang.c mailing list