C
Function Pointers
Store function addresses for callbacks and dispatch tables.
By EZ4Code Team
function-pointercallback
Code
#include <stdio.h>
// A function pointer type
typedef int (*BinOp)(int, int);
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int apply(BinOp op, int a, int b) {
return op(a, b);
}
int main(void) {
BinOp op = add;
printf("add(2,3) = %d\n", op(2, 3));
op = mul;
printf("mul(2,3) = %d\n", op(2, 3));
// Dispatch table
BinOp table[] = {add, mul};
for (int i = 0; i < 2; i++) {
printf("table[%d](4,5) = %d\n", i, table[i](4, 5));
}
return 0;
}Explanation
A function pointer stores the address of a function so it can be called indirectly, enabling callbacks and dispatch tables. The typedef BinOp makes the pointer-to-function syntax readable. Functions like qsort use this mechanism to let callers supply their own comparison logic.
More C Snippets
Pointer Basics
Declare pointers, dereference, and walk an array with pointer arithmetic.
Memory Management
Allocate, resize, and free heap memory with malloc, realloc, and free.
String Operations
Use string.h helpers for length, copy, concat, compare, and tokenize.
File I/O
Open, read, write, and close files using the stdio FILE API.
Structs
Group related fields with typedef and pass by pointer for mutation.
Preprocessor Macros
Define object-like and function-like macros with conditional compilation.