0 day streak
c / expert
Snippet

Generic Callbacks via Function Pointers

Function pointers enable polymorphism in C. By using 'void*' parameters in a callback signature, you can create generic algorithms (like qsort) that operate on any data type. The callback abstracts the logic (e.g., comparison) while the algorithm handles the execution flow.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
typedef int (*compare_fn)(const void*, const void*);
int compare_ints(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
void sort_and_print(int *arr, size_t n, compare_fn cmp) {
qsort(arr, n, sizeof(int), cmp);
for(size_t i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
}
int main() {
int data[] = {42, 7, 101, -5};
sort_and_print(data, 4, compare_ints);
return 0;
}
Breakdown
1
typedef int (*compare_fn)(const void*, const void*);
Defines a type for a function taking two generic pointers and returning an integer.
2
(*(int*)a - *(int*)b)
Casts the generic void pointers back to the specific type for comparison.