C Function Pointer as Argument
Syntax
return_type function_name(data_type (*pointer_variable_name)(data_type))
Example
#include<stdio.h>
void display(char *);
void function1(int, char*);
void function2(int, char*);
void execute(void (*)(int, char*), int, char*);
int main(){
char *str = "Hello World";
execute(function1, 10, str);
execute(function2, 20, str);
return 0;
}
void function1(int x, char* str){
printf("Function 1: %s, %d\n", str, x);
}
void function2(int x, char* str){
printf("Function 2: %s, %d\n", str, x);
}
void execute(void (*function_ptr)(int, char*), int x, char* str){
(*function_ptr)(x, str);
}
Output
Function 1: Hello World, 10
Function 2: Hello World, 20
Explanation
C function pointers can be passed as arguments to other functions. To do this, we declare a function pointer as a parameter of the function and pass a function pointer as an argument to this function. The function pointer is then called inside the function.
Use
Function pointers as arguments can be used for implementing callback functions and for dynamic function selection. They can also be used for implementing generic data structures, such as linked lists and trees, where the operations on the data are provided by the function pointers.
Important Points
- Function pointers can be declared as parameters of a function.
- The syntax for declaring a function pointer as a parameter is
data_type (*pointer_variable_name)(data_type)
. - Function pointers can be called from within the function that receives them as arguments using the syntax
(*function_ptr)(argument_list)
.
Summary
In summary, the C function pointer as an argument is a powerful tool for implementing callback functions and dynamic function selection. It provides a great deal of flexibility and can be used to create generic data structures and complex algorithms. By understanding the syntax and use cases for function pointers as arguments, you can greatly expand your abilities as a C programmer.