1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
void report_comparison(const void* a_lhs, const void* a_rhs, int (*compare_fn)(const void*, const void*)) {
// 'a_lhs' means "address of left-hand side"
int compare_result = compare_fn(a_lhs, a_rhs);
if(compare_result < 0) {
printf("lhs comes before rhs\n");
}
else if(compare_result == 0) {
printf("lhs is equivalent to rhs\n");
}
else {
printf("lhs comes after rhs\n");
}
}
int compare_ints(const void* a_lhs, const void* a_rhs) {
return *(const int*)a_lhs - *(const int*)a_rhs;
// Note: if lhs < rhs, this is negative; if lhs > rhs this is positive; else 0
}
int main(int argc, char* argv[]) {
int lhs = 5555;
int rhs = 5555;
printf("Compare integers: %d vs. %d\n", lhs, rhs);
report_comparison(&lhs, &rhs, compare_ints);
printf("\n");
char* lhs_str = "apple";
char* rhs_str = "banana";
printf("Compare strings: %s vs. %s\n", lhs_str, rhs_str);
report_comparison(&lhs_str, &rhs_str, (int(*)(const void*, const void*))strcmp);
//... oid* a_lhs, const void* a_rhs, int (*compare_fn)(const void*, const void*)) {
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.