Pointers to Functions in C
Pointers to functions allow you to store and pass around the addresses of functions. This provides flexibility in function invocation and enables dynamic function dispatch.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
int (*operation)(int, int); // Pointer to function declaration
operation = add; // Assign address of add function
printf("Addition: %d\n", operation(3, 2));
operation = subtract; // Assign address of subtract function
printf("Subtraction: %d\n", operation(3, 2));
operation = multiply; // Assign address of multiply function
printf("Multiplication: %d\n", operation(3, 2));
return 0;
}
No comments:
Post a Comment