C: the strategy pattern with function pointers

The strategy pattern selects an algorithm at run time. In C the natural tool is a function pointer. The standard library's qsort sorts any array and asks the caller for a comparison function, so the same sorting code gives ascending, descending, or any other order depending on the strategy passed in.

C
#include <stdio.h>
#include <stdlib.h>

static int ascending(const void *x, const void *y) {
  int a = *(const int *)x;
  int b = *(const int *)y;
  return (a > b) - (a < b);
}

static int descending(const void *x, const void *y) {
  return ascending(y, x);
}

static int by_last_digit(const void *x, const void *y) {
  int a = *(const int *)x % 10;
  int b = *(const int *)y % 10;
  return (a > b) - (a < b);
}

static void show(const char *label, const int *values, int n) {
  printf("%s:", label);
  for (int i = 0; i < n; i++) {
    printf(" %d", values[i]);
  }
  printf("\n");
}

int main(void) {
  int original[] = {42, 7, 19, 33, 8};
  int n = (int)(sizeof original / sizeof original[0]);
  int (*strategies[])(const void *, const void *) = {ascending, descending, by_last_digit};
  const char *names[] = {"ascending", "descending", "by last digit"};

  for (int s = 0; s < 3; s++) {
    int copy[5];
    for (int i = 0; i < n; i++) {
      copy[i] = original[i];
    }
    qsort(copy, (size_t)n, sizeof copy[0], strategies[s]);
    show(names[s], copy, n);
  }
  return 0;
}
Read the full lesson