C Function Pointer
Syntax
The syntax for declaring and using a function pointer in C is as follows:
return_type (*function_ptr_name)(arg_type1, arg_type2, ..., arg_typeN);
Example
Here is an example of how to use a function pointer in C:
#include <stdio.h>
// function prototype
int add(int x, int y);
int main() {
// declaring a function pointer
int (*func_ptr)(int, int);
// assigning the function pointer to the function
func_ptr = &add;
// using the function pointer to call the function
int result = (*func_ptr)(10, 20);
printf("Result: %d\n", result);
return 0;
}
// function definition
int add(int x, int y) {
return x + y;
}
Output
Result: 30
Explanation
A function pointer is a pointer that points to the memory address of a function. The function pointer can be used to call the function that it points to. To declare a function pointer, we must specify the return type of the function and the argument types. Then we declare the function pointer variable itself.
To assign a function to a function pointer, we can use the & operator to take the address of the function and assign it to the function pointer. To call the function that the pointer points to, we must dereference the pointer using the * operator and pass in the arguments.
Use
Using function pointers in C can be useful when:
- passing functions as arguments to other functions
- dynamically selecting which function to call based on user input or other factors
- implementing callback functions to handle events in GUI programming.
Important Points
- A function pointer can be used to call a function indirectly.
- When declaring a function pointer, we must specify the return type and argument types of the function it will point to.
- A function pointer can be assigned to a function using the & operator.
- To call the function pointer, we use the * operator to dereference the pointer and pass in arguments.
Summary
In C, function pointers allow us to call a function indirectly through a pointer. This can be useful in a variety of situations, such as passing functions as arguments, dynamically selecting which function to call, and implementing callback functions. Understanding the syntax, uses, and important points of function pointers can help you write more flexible, powerful, and efficient code.