On this page
  1. Function Pointers & Callbacks
  2. Contents
  3. Callback Typedefs & qsort
  4. Vtable-Style Polymorphism in Pure C

Function Pointers & Callbacks

Prev: Dynamic Memory & Allocators | Up: pointers_and_memory | Next: Undefined Behavior & Sanitizers
Rel: qsort & bsearch, Polymorphism & Dispatch
Ref: cppreference — qsort
Tags: #public #prog #c #pointers #callbacks


Contents


Callback Typedefs & qsort

Always typedef function pointer types for readability. Here is the standard overflow-safe comparator for qsort:

#include <stdlib.h>

static int cmp_int(const void *a, const void *b) {
    int lhs = *(const int *)a;
    int rhs = *(const int *)b;
    return (lhs > rhs) - (lhs < rhs); // Avoids (lhs - rhs) signed overflow!
}

Vtable-Style Polymorphism in Pure C

C implements runtime interfaces (like Linux VFS or CPython PyTypeObject) by pairing a data pointer with a struct of function pointers:

typedef struct {
    double (*area)(const void *self);
} ShapeVTable;

typedef struct {
    const ShapeVTable *vtable;
    void *data;
} Shape;

Linked from

Related notes