In C, a function pointer is a pointer that points to a function instead of pointing to a data variable. Function pointers can be useful in scenarios where you want to choose which function to call at runtime or pass a function as an argument to another function.
Definition:
A function pointer in C is a variable that stores the address of a function. It points to the memory address where the function is loaded.
Syntax:
return_type (*pointer_name)(parameter_types);
Here, return_type is the type of value the function returns, pointer_name is the name of the function pointer, and parameter_types are the types of parameters the function takes.
Example:
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b;
}// Function to subtract two numbers
int subtract(int a, int b) {
return a – b;
}int main() {
// Declare function pointers
int (*operation)(int, int);// Assign the address of the add function to the pointer
operation = add;// Use the function pointer to call the add function
int result = operation(5, 3);
printf(“Result of addition: %dn”, result);// Assign the address of the subtract function to the pointer
operation = subtract;// Use the function pointer to call the subtract function
result = operation(5, 3);
printf(“Result of subtraction: %dn”, result);return 0;
}
Explanation:
- int (*operation)(int, int);: Declare a function pointer named operation that can point to a function taking two integers and returning an integer.
- operation = add;: Assign the address of the add function to the operation pointer.
- result = operation(5, 3);: Use the function pointer to call the function it points to.
Output:
Result of addition: 8
Result of subtraction: 2
In this program, the function pointer operation is used to dynamically switch between the add and subtract functions. This demonstrates the flexibility of function pointers in choosing which function to call at runtime.