In C programming, function pointers are variables that store the memory address of a function. They can be used to call a function indirectly and are often used to implement callbacks and function arrays.
Here’s an example of how to use function pointers in C:
#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 a = 10, b = 5;
int (*func_ptr)(int, int); // declare function pointer variable
// assign function pointer to the 'add' function
func_ptr = &add;
// call the 'add' function through the function pointer
int result = (*func_ptr)(a, b);
printf("Result: %dn", result);
// assign function pointer to the 'subtract' function
func_ptr = &subtract;
// call the 'subtract' function through the function pointer
result = (*func_ptr)(a, b);
printf("Result: %dn", result);
// assign function pointer to the 'multiply' function
func_ptr = &multiply;
// call the 'multiply' function through the function pointer
result = (*func_ptr)(a, b);
printf("Result: %dn", result);
return 0;
}
In this example, we define three functions add, subtract, and multiply, which take two integers as arguments and return an integer value. We then declare a function pointer variable func_ptr that takes two integers as arguments and returns an integer value.
We first assign func_ptr to the add function using the & operator to get the address of the function. We then call the add function indirectly using the function pointer (*func_ptr)(a, b).
We then reassign func_ptr to the subtract function and call it using the function pointer, and finally, we reassign func_ptr to the multiply function and call it again.
This is just one example of how function pointers can be used in C. They are a powerful feature of the language that can be used to implement a wide variety of functionality, from callbacks to function arrays to dynamic function calls.