Path: utzoo!mnetor!tmsoft!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!julius.cs.uiuc.edu!apple!netcom!teda!ditka!mcdchg!tellab5!balr!clrcom!rmartin From: rmartin@clear.com (Bob Martin) Newsgroups: comp.lang.c++ Subject: Re: Comparison functions for qsort() and bsearch() Keywords: Sun, C++ Message-ID: <1990Dec26.160636.15566@clear.com> Date: 26 Dec 90 16:06:36 GMT References: <1990Dec20.114821@roadster.bellcore.com> <3069@lupine.NCD.COM> <277640DD.4A70@tct.uucp> Organization: Clear Communications, Inc. Lines: 47 In article <277640DD.4A70@tct.uucp> chip@tct.uucp (Chip Salzenberg) writes: >[This discussion is relevant to both the C and C++ languages; hence > the cross-post. Please direct followups appropriately.] This followup involves only C++ and the newsgroup has been adjusted accordingly. > >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. I dissagree. As Ron said in his article. It is always possible to cast a pointer to anything to a pointer to void. But it is not guaranteed that you can cast a pointer to void back to its original. Case in point is a class derived from multiple bases: class AB : public A, public B; Now take the following variable: AB *ab; The following two casts work just fine: (A *)ab; (B *)ab; But the following, though it may compile, is likely not to work properly because it miscalculates the address of at least one of the base classes. (A *)(void *)ab; or (B *)(void *)ab; Yet if qsort is to sort objects of type AB, then this is precicely what the void* implementation of compar would be asked to do! Worse yet the compiler can't catch this error and will thus allow corrupted pointers loose in your program. Amost certainly the program will crash. > >Remember that qsort() cannot know the real type of the objects it is >sorting. Again I agree with Ron. qsort/bsearch should be templated functions. Better yet they should be member functions embedded in some kind of container class. -- +-Robert C. Martin-----+:RRR:::CCC:M:::::M:| Nobody is responsible for | | rmartin@clear.com |:R::R:C::::M:M:M:M:| my words but me. I want | | uunet!clrcom!rmartin |:RRR::C::::M::M::M:| all the credit, and all | +----------------------+:R::R::CCC:M:::::M:| the blame. So there. |