Function Pointer as Argument in C
A function pointer as an argument allows you to pass a function to another function. This enables a high level of flexibility and modularity in your code, as you can change the behavior of a function dynamically by passing different functions as arguments.
Definition
In C, you can pass function pointers as arguments to other functions. This allows the called function to invoke the passed function. Function pointers as arguments are commonly used in callback mechanisms, event-driven programming, and sorting algorithms where you want to define custom behavior that can change at runtime.
The syntax for passing a function pointer as an argument to another function is:
Syntax:
return_type function_name(return_type (*pointer_name)(parameter_types), parameter_types);
Example: Function Pointer as Argument
This example demonstrates how to pass a function pointer as an argument to another function to perform operations on numbers.
Example Code:
#include <stdio.h>
// Function that performs an operation on two integers
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
// Function that takes a function pointer as an argument
int calculate(int (*operation)(int, int), int x, int y) {
return operation(x, y); // Call the function passed as argument
}
int main()
{
int result;
// Pass 'add' function pointer
result = calculate(add, 10, 5);
printf("Addition: %d\n", result);
// Pass 'subtract' function pointer
result = calculate(subtract, 10, 5);
printf("Subtraction: %d\n", result);
return 0;
}
Output
Addition: 15
Subtraction: 5
Subtraction: 5
Key Points
- Function pointers can be passed as arguments to other functions, allowing dynamic behavior and flexibility.
- By using function pointers as arguments, you can implement callback functions, where the called function executes a function provided by the caller.
- The function pointer argument must be declared with the correct return type and parameter types to match the function being passed.
- Function pointers as arguments are commonly used in cases like sorting algorithms, where the comparison function can change at runtime.
- Using function pointers in this way allows for highly flexible and reusable code.