Generic Compare
Part of the Object Oriented Programming section of Coddy's C journey — lesson 52 of 61.
Generic functions like qsort and bsearch in C's standard library need a way to compare elements without knowing their types. The solution is a comparison function — a function you write that the generic algorithm calls whenever it needs to compare two items.
The standard signature for comparison functions is:
int compare(const void* a, const void* b);Both parameters are const void* because the generic function doesn't know what type you're sorting. The return value follows a specific convention:
| Return Value | Meaning |
|---|---|
| Negative | a comes before b |
| Zero | a equals b |
| Positive | a comes after b |
Inside your comparison function, you cast the void* pointers to the actual type and compare the values. Here's how to compare integers:
int compare_ints(const void* a, const void* b) {
int val_a = *(const int*)a;
int val_b = *(const int*)b;
return val_a - val_b;
}The subtraction trick works well for integers: if a is smaller, the result is negative; if equal, zero; if larger, positive. This function can now be passed to qsort to sort an integer array in ascending order.
Challenge
EasyWrite a function compare_ints that compares two integers following the standard comparison function convention used by generic algorithms like qsort.
Your function should compare the two values and return a result that indicates their ordering relationship.
Return Value Convention:
- Return a negative value if the first integer comes before the second (first < second)
- Return zero if both integers are equal
- Return a positive value if the first integer comes after the second (first > second)
Parameters:
a(int): The first integer to compareb(int): The second integer to compare
Returns: An integer indicating the ordering: negative if a < b, zero if a == b, positive if a > b.
Hint: The subtraction trick from the lesson provides an elegant one-line solution.
Cheat sheet
Comparison functions enable generic algorithms like qsort and bsearch to compare elements without knowing their types.
The standard signature for comparison functions:
int compare(const void* a, const void* b);Parameters are const void* because the generic function doesn't know the type being sorted.
Return value convention:
| Return Value | Meaning |
|---|---|
| Negative | a comes before b |
| Zero | a equals b |
| Positive | a comes after b |
Inside the comparison function, cast void* pointers to the actual type and compare values:
int compare_ints(const void* a, const void* b) {
int val_a = *(const int*)a;
int val_b = *(const int*)b;
return val_a - val_b;
}The subtraction trick works for integers: if a is smaller, the result is negative; if equal, zero; if larger, positive.
Try it yourself
int compare_ints(int a, int b) {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box7Function Pointers
Declaring Function PointersCalling Function PointersTypedef for Function PointersPassing Functions as ArgumentsRecap: Calculator Dispatch10Generic Containers
Void Pointers RecapGeneric WrapperGeneric SwapGeneric CompareRecap: Generic Array2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy