What is the implementation principle of function pointers and callback functions in C language?
Function Pointer Basics:
-
Function Pointer Declaration
c// return_type (*pointer_name)(parameter_list) int (*func_ptr)(int, int); // Pointer to function int add(int a, int b) { return a + b; } func_ptr = add; // Call function through pointer int result = func_ptr(3, 5); // Equivalent to add(3, 5) -
Function Pointer Arrays
cint (*operations[])(int, int) = {add, subtract, multiply}; int result = operations[0](10, 5); // Call add -
As Function Parameter
cvoid process_array(int *arr, int size, int (*callback)(int)) { for (int i = 0; i < size; i++) { arr[i] = callback(arr[i]); } }
Callback Function Implementation:
-
Sorting Callback
cint compare_asc(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int arr[] = {5, 2, 8, 1, 9}; qsort(arr, 5, sizeof(int), compare_asc); -
Event Handling Callback
ctypedef void (*EventHandler)(void); void on_click() { printf("Button clicked!\n"); } void register_event(EventHandler handler) { handler(); // Trigger callback } -
Async Operation Callback
ctypedef void (*AsyncCallback)(int result, void *user_data); void async_operation(AsyncCallback callback, void *data) { // Simulate async operation int result = perform_task(); callback(result, data); }
Advanced Applications:
-
State Machine Implementation
ctypedef void (*StateHandler)(void); void state_idle() { /* ... */ } void state_running() { /* ... */ } void state_paused() { /* ... */ } StateHandler states[] = {state_idle, state_running, state_paused}; int current_state = 0; states[current_state](); -
Strategy Pattern
ctypedef int (*Strategy)(int, int); int strategy_max(int a, int b) { return a > b ? a : b; } int strategy_min(int a, int b) { return a < b ? a : b; } void execute_strategy(Strategy strategy, int x, int y) { printf("Result: %d\n", strategy(x, y)); }
Important Considerations:
- Function pointer types must match exactly
- Null pointer checks are necessary
- Context management in callback functions is important