Function Pointers and Callbacks in C
Function pointers allow you to store the address of a function and invoke it later. They are particularly useful when combined with callback mechanisms, where functions can be passed as arguments to other functions.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int calculator(int (*operation)(int, int), int a, int b) {
return operation(a, b);
}
int main() {
int result1 = calculator(add, 5, 3);
int result2 = calculator(subtract, 5, 3);
printf("Result 1: %d\n", result1);
printf("Result 2: %d\n", result2);
return 0;
}
In this example, the calculator function takes a function pointer as an argument and invokes it with two integer arguments. This allows for dynamic function dispatching and flexibility in the operations performed.
No comments:
Post a Comment