On this page
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
- tuts/c/pointers_and_memory Linked here; links to this page; shared tags: #c, #pointers, #prog
- tuts/c/pointers_and_memory/dynamic_memory_and_allocators Linked here; links to this page; shared tags: #c, #prog
- tuts/c/pointers_and_memory/undefined_behavior_and_sanitizers Linked here; links to this page; shared tags: #c, #prog
- tuts/c/stdlib/stdlib_and_string_h Linked here; links to this page; shared tags: #c, #prog
- tuts/programming/paradigms/object_oriented_programming Linked here; shared tags: #prog
- tuts/rust/ownership_and_internals/traits_generics_and_dispatch links to this page; shared tags: #prog
- tuts/c/pointers_and_memory/pointers_and_pointer_arithmetic shared tags: #c, #pointers, #prog
- tuts/c shared tags: #c, #prog
- tuts/c/builtins shared tags: #c, #prog
- tuts/c/builtins/__FILE__ shared tags: #c, #prog