Function Pointers in C are pointers that point to the address of a function. They are used to call functions indirectly and allow passing functions as arguments to other functions.
return_type (*pointer_name)(parameter_types);
Example:
int (*fptr)(int, int); // Pointer to a function that returns int and takes two int parameters
Callback Functions: Used in libraries to pass custom behavior to functions (e.g., sorting algorithms or event handling).
void callback_function(int val) { /* do something */ }
void register_callback(void (*callback)(int)) {
callback(10); // Calls callback_function
}
Dynamic Dispatch: Choosing functions dynamically at runtime, such as state machines or virtual function tables.
typedef void (*StateFunction)();
StateFunction state = someFunction;
state(); // Calls someFunction dynamically
Plugin Mechanism: Allow swapping functionality without altering the core code.
Efficient Code: Reduces code duplication by reusing behavior in different contexts.
Example:
#include <stdio.h>
void add(int a, int b) { printf("Sum: %d\\\\n", a + b); }
void subtract(int a, int b) { printf("Difference: %d\\\\n", a - b); }
int main() {
void (*operation)(int, int); // Function pointer
operation = add; // Assign function to pointer
operation(5, 3); // Call add(5, 3)
operation = subtract;
operation(5, 3); // Call subtract(5, 3)
}