Concept
How do you implement a comparator for integers in C?
ComputerScienceOne / Comparator Functions
"To write a comparator function that orders integers in ascending order, the generic pointers must first be converted into pointers to the specific type being compared. In general, a void pointer cannot be dereferenced because the number of bytes a void type takes is undefined. Dereferencing an int * or double * is possible because the compiler knows how many bytes each type takes. The first step is therefore to make the pointers int pointers by doing an explicit type cast:\n\nconst int *x = (const int *) a;\n\nconst int *y = (const int *) b;\n\nThe const keyword is preserved to ensure that the comparator does not make changes to the variables. The resulting comparator compares the dereferenced integer values and returns a negative value, zero, or a positive value:\n\nint cmpInt(const void *a, const void *b) {\n\nconst int *x = (const int *) a;\n\nconst int *y = (const int *) b;\n\nif(*x < *y) {\n\nreturn -1;\n\n} else if(*x == *y) {\n\nreturn 0;\n\n} else {\n\nreturn 1;\n\n}\n\n}\n\nTo order integers in the opposite direction, another comparator could reverse the comparisons or values. Even simpler, the existing comparator can be reused by flipping its arguments:\n\nint cmpIntDesc(const void *a, const void *b) {\n\nreturn cmpInt(b, a);\n\n}\n\nThese examples illustrate the standard implementation pattern of comparator functions: make the general const void * pointers into const pointers to the specific type by making an explicit type cast; use the state of the type, including one or more components when comparing structures, to determine the order; and return an integer that expresses the desired order."
Related Ideas
- How does the C standard library function qsort() work?ComputerScienceOne · Examples
- How are generic getMax() functions used with integers and structures?ComputerScienceOne · Function Pointers
- How should a comparator handle an array of structure pointers with NULL values?ComputerScienceOne · Sorting Pointers to Elements
- How can qsort() sort an array of strings using pointers?ComputerScienceOne · Sorting Pointers to Elements
- How can pointer arithmetic and comparators implement a generic getMax()?ComputerScienceOne · Function Pointers
- What is a function pointer and how is it declared?ComputerScienceOne · Function Pointers
- How does strcmp() compare the contents of two strings in C?ComputerScienceOne · Comparisons
- How are qsort(), lfind(), and bsearch() used in C examples?ComputerScienceOne · Examples