乐闻世界logo
搜索文章和话题

What is the implementation principle of function pointers and callback functions in C language?

2月18日 17:13

What is the implementation principle of function pointers and callback functions in C language?

Function Pointer Basics:

  1. 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)
  2. Function Pointer Arrays

    c
    int (*operations[])(int, int) = {add, subtract, multiply}; int result = operations[0](10, 5); // Call add
  3. As Function Parameter

    c
    void process_array(int *arr, int size, int (*callback)(int)) { for (int i = 0; i < size; i++) { arr[i] = callback(arr[i]); } }

Callback Function Implementation:

  1. Sorting Callback

    c
    int 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);
  2. Event Handling Callback

    c
    typedef void (*EventHandler)(void); void on_click() { printf("Button clicked!\n"); } void register_event(EventHandler handler) { handler(); // Trigger callback }
  3. Async Operation Callback

    c
    typedef 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:

  1. State Machine Implementation

    c
    typedef 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]();
  2. Strategy Pattern

    c
    typedef 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
标签:C语言