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
43
44
45
46
47
48
#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) {
    const int* a_lhs_int = a_lhs;   // no typecast needed for ▒▒▒* ↔ void*
    const int* a_rhs_int = a_rhs;   // no typecast needed for ▒▒▒* ↔ void*
    int lhs = *a_lhs_int;
    int rhs = *a_rhs_int;
    return lhs - rhs;  // will be <0 if lhs < rhs; ==0 if lhs==rhs, >0 if lhs > rhs
}


int compare_strings(const void* a_lhs, const void* a_rhs) {
    return strcmp(a_lhs, a_rhs);
}

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, strcmp);
    
    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.