program to explain function pointers.
Unlocking the Power of Function Pointers: Practical C Programming
Function pointers are pointers that point to the address of functions. They allow you to store the address of a function and later call that function through the pointer. This can be particularly useful when you want to choose which function to call at runtime or when you want to pass functions as arguments to other functions.
C program that explains function pointers:
#include <stdio.h>
// Function prototypes
int add(int a, int b);
int subtract(int a, int b);
int main() {
// Declare function pointers
int (*operation)(int, int);
// Assign function addresses to function pointers
operation = add;
int result = operation(5, 3); // Call add function through the pointer
printf("Addition result: %d\n", result);
operation = subtract;
result = operation(8, 4); // Call subtract function through the pointer
printf("Subtraction result: %d\n", result);
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
In this program:
-
We include the standard input/output header stdio.h.
-
We declare two function prototypes: add and subtract.
-
In the main function:
- We declare a function pointer operation that can point to functions taking two int arguments and returning an int.
- We assign the address of the add function to the operation pointer and use it to call the add function.
- We then reassign the operation pointer to point to the subtract function and use it to call the subtract function.
-
Below the main function, we define the add and subtract functions as specified in the prototypes.
When you run this program, you'll see the following output:
Addition result: 8
Subtraction result: 4
In this example, we've demonstrated how to use function pointers to dynamically choose and call different functions based on the function pointer assignments. The operation pointer acts as a switch, allowing us to call different functions using the same pointer.