Skip to content

C Function Pointers

Function pointers store the address of functions and allow dynamic function calls.

1. Function Pointer Declaration

c
int (*func_ptr)(int, int);  // pointer to function taking two ints, returning int

2. Function Pointer Assignment

c
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }

func_ptr = add;  // assign function

3. Using Function Pointers

c
int result = func_ptr(5, 3);  // calls add(5, 3) = 8

func_ptr = subtract;
result = func_ptr(5, 3);  // calls subtract(5, 3) = 2

4. Function Pointer Arrays

c
int (*operations[])(int, int) = {add, subtract, multiply, divide};
int result = operations[0](5, 3);  // calls add

5. Callback Functions

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

Content is for learning and research only.