stdlib: fix qsort example in manual

* manual/search.texi (Comparison Functions, Array Sort Function):
Sort an array of long ints, not doubles, to avoid hassles
with NaNs.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
This commit is contained in:
Paul Eggert 2024-02-01 11:52:46 -08:00
parent 275607a07f
commit e7b90e6e60

View file

@ -35,19 +35,22 @@ second, zero if they are ``equal'', and positive if the first argument
is ``greater''. is ``greater''.
Here is an example of a comparison function which works with an array of Here is an example of a comparison function which works with an array of
numbers of type @code{double}: numbers of type @code{long int}:
@smallexample @smallexample
int int
compare_doubles (const void *a, const void *b) compare_long_ints (const void *a, const void *b)
@{ @{
const double *da = (const double *) a; const long int *la = a;
const double *db = (const double *) b; const long int *lb = b;
return (*da > *db) - (*da < *db); return (*la > *lb) - (*la < *lb);
@} @}
@end smallexample @end smallexample
(The code would have to be more complicated for an array of @code{double},
to handle NaNs correctly.)
The header file @file{stdlib.h} defines a name for the data type of The header file @file{stdlib.h} defines a name for the data type of
comparison functions. This type is a GNU extension. comparison functions. This type is a GNU extension.
@ -183,16 +186,16 @@ in the array before making some comparisons. The only way to perform
a stable sort with @code{qsort} is to first augment the objects with a a stable sort with @code{qsort} is to first augment the objects with a
monotonic counter of some kind. monotonic counter of some kind.
Here is a simple example of sorting an array of doubles in numerical Here is a simple example of sorting an array of @code{long int} in numerical
order, using the comparison function defined above (@pxref{Comparison order, using the comparison function defined above (@pxref{Comparison
Functions}): Functions}):
@smallexample @smallexample
@{ @{
double *array; long int *array;
int size; size_t nmemb;
@dots{} @dots{}
qsort (array, size, sizeof (double), compare_doubles); qsort (array, nmemb, sizeof *array, compare_long_ints);
@} @}
@end smallexample @end smallexample