Function Pointers
Function Pointers
In C, functions have addresses in memory just like variables. A function pointer stores the address of a function, letting you call functions indirectly.
Declaring Function Pointers
The syntax mirrors the function signature, with (*name) replacing the function name:
int add(int a, int b) { return a + b; }
// Declare a pointer to a function taking two ints, returning int
int (*op)(int, int) = add;
printf("%d\n", op(3, 4)); // 7
"Number One, you have the conn." The captain doesn't do the task -- he points to whoever should. That's a function pointer.
Why Function Pointers?
They let you write generic code. For example, an apply function that works with any operation:
int apply(int (*f)(int, int), int x, int y) {
return f(x, y);
}
int mul(int a, int b) { return a * b; }
printf("%d\n", apply(add, 2, 3)); // 5
printf("%d\n", apply(mul, 2, 3)); // 6
Callback Pattern
Function pointers enable callbacks -- passing a function to be called later:
void for_each(int *arr, int n, void (*action)(int)) {
for (int i = 0; i < n; i++) {
action(arr[i]);
}
}
void print_item(int x) {
printf("%d\n", x);
}
int nums[] = {10, 20, 30};
for_each(nums, 3, print_item);
Your Task
Write three functions: int add(int a, int b), int sub(int a, int b), and int mul(int a, int b). Then write int apply(int (*f)(int, int), int a, int b) that calls the function pointer. Use apply to compute and print: 10+3, 10-3, 10*3.