473,766 Members | 2,064 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparison function in qsort()

Hello,

I've come across the following comparison function used as the 4th
parameter in qsort()

int cmp(const void *px, const void *py)
{
const double *x = px, *y = py;
return (*x > *y) - (*x < *y);
}

It came "as-is" i.e. no comments.

Is it good style to write comparison functions that way?

Should the return values be made more explicit? Or would it be enough to
add comments explaining why the function (usually) works?

--
Regards, Spoon
Apr 12 '06
14 5021
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.or g> wrote:
The code above, "return (*x > *y) - (*x < *y);", is also probably
better-behaved in the presence of infinities and NaNs, at least quiet
NaNs.


And this is just the sort of thing that many programmers will not be
aware of, so the lack of a comment is inexcusable.

-- Richard
Apr 18 '06 #11
In article <e2***********@ pc-news.cogsci.ed. ac.uk> ri*****@cogsci. ed.ac.uk (Richard Tobin) writes:
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.or g> wrote:
The code above, "return (*x > *y) - (*x < *y);", is also probably
better-behaved in the presence of infinities and NaNs, at least quiet
NaNs.


And this is just the sort of thing that many programmers will not be
aware of, so the lack of a comment is inexcusable.


What is better behaved? It depends on how the compiler works what is
returned in the case of NaNs, and it is not sure that what is returned
is also consistent. (And be aware that the comparison function must
be consistent, otherwise sorting can fail.) But it works well in the
case of infinities and when overflow occurs. Consider a compiler that
uses the compare greater instruction. If x is a NaN, both comparisons
will return false, and so the returned value is 0. Now when the
compiler uses the compare greater or uncomparable instruction, in that
case both comparisons return true, and the function will again return 0.
So with these scenarios the comparison function will tell a NaN is
equal to any other number.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Apr 18 '06 #12
On Tue, 18 Apr 2006 11:55:15 GMT,
Dik T. Winter <Di********@cwi .nl> wrote
in Msg. <Ix********@cwi .nl>
So with these scenarios the comparison function will tell a NaN is
equal to any other number.


....which is exactly as reasonable as making NaN greater or smaller than
any other number, or erratically switching between behaviors. I admit
the latter case is the worst because it's hard to debug, but in any case
an array with NaNs in it is unsortable by size anyway.

robert
Apr 18 '06 #13
"Robert Latest" <bo*******@yaho o.com> wrote in message
news:4a******** ****@individual .net...
On Tue, 18 Apr 2006 11:55:15 GMT,
Dik T. Winter <Di********@cwi .nl> wrote
in Msg. <Ix********@cwi .nl>
So with these scenarios the comparison function will tell a NaN is
equal to any other number.
...which is exactly as reasonable as making NaN greater or smaller than
any other number,


Uh, no it's not. If the comparison function doesn't impose a strict
weak ordering on all values, a typical sort can loop or overwrite
storage. NaN should be either greater or less than any finite value,
comparing equal only to another NaN.
or erratically switching between behaviors. I admit
the latter case is the worst because it's hard to debug, but in any case
an array with NaNs in it is unsortable by size anyway.


Not true. If you're lucky, your compiler will either:

a) evaluate x != x as true for a NaN, or

b) supply some form of the C99 isnan(x) generic-function macro.

You comparison function is messier, but writable. And robust in the
presence of NaNs.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Apr 18 '06 #14
On Tue, 18 Apr 2006 09:43:22 -0400,
P.J. Plauger <pj*@dinkumware .com> wrote
in Msg. <X6************ *************** ***@giganews.co m>
You comparison function is messier, but writable. And robust in the
presence of NaNs.


After reading the C Standard and after a bit of thinking I decided
that you're right. A comparison function should compare NaNs greater or
smaller than any number, and comparison of two NaNs should evaluate as
equal.

robert
Apr 18 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1730
by: Debashish Chakravarty | last post by:
Would it have been a good idea if the comparison function in quicksort took three const void * parameters in, the third one for extra information that might be required to compare the two objects, I think the only way one can pass the information is by using global or static variables.
0
1166
by: Debashish Chakravarty | last post by:
I am sorry, I meant qsort function not quicksort (I know qsort might not implement quicksort) and since I am constrained to use google I cannot reply to my previous post and hence his new post, apologies for the inconvienience.
3
2307
by: Dennis Chang | last post by:
Hi all, I was reading about function pointers and came across something which intrigued me. K&R2 calls qsort (pg.119) within main as so: qsort( (void **) lineptr, 0, nlines-1, (int (*) (void *, void*))(numeric ? numcmp : strcmp) ); I guess what interests me is the nameless function pointer and then the
5
2535
by: Danilo Kempf | last post by:
Folks, maybe one of you could be of help with this question: I've got a relatively portable application which I'm extending with a plugin interface. While portability (from a C perspective) is going to hell just by using dlopen()/LoadLibrary() respectively, I'm still trying to get it as clean as possible. I have a number of different quantums of data and a number of plugins. Since any plugin can (and possibly will) touch any quantum...
6
4468
by: aurgathor | last post by:
Howdy, How do I pass some function a generic comparison function? I figured out one non-generic case, but since this code got parameter declarations in two places, it's obviously not generic. TIA #include <stdio.h>
9
3473
by: christer-sandberg | last post by:
When I typecast a function and call it trough the casted pointer (se code below) I get the warnings: warning: function called through a non-compatible type if this code is reached, the program will abort and the gcc generates abort code for the call. This happens when I use gcc 3.4 but not when I use 3.3. Is there any flag that can change this behavior? I am aware that ANSI-99 says (in 6.3.2.3-8): "If a converted pointer is used to call...
17
3602
by: Charles Sullivan | last post by:
The library function 'qsort' is declared thus: void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); If in my code I write: int cmp_fcn(...); int (*fcmp)() = &cmp_fcn; qsort(..., fcmp); then everything works. But if instead I code qsort as:
9
5088
by: cmk128 | last post by:
Hi Why put * in front of the function name in the declaration? int (*write)(struct inode *, struct file *, const char *, int); thanks from Peter (cmk128@hotmail.com)
26
25607
by: tnowles00 | last post by:
Hi friend, what is the use of function pointer in c language and where it is useful? tell with simple example...? plz help me.
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10008
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9837
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7381
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5279
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.