- In C, a function pointer is a pointer that stores the address of a function. It can be used to invoke the function indirectly, through the function pointer. This can be useful in certain scenarios, such as when you want to pass a function as an argument to another function, or when you want to use a function as a callback.
- Here’s an example of how to declare a function pointer in C:
int (*function_ptr)(int, int);
- This declares a function pointer called function_ptr that points to a function that takes two int arguments and returns an int.
- To assign a function to a function pointer, you can use the address-of operator &:
int add(int x, int y) {
return x + y;
}
function_ptr = &add;
- To invoke the function through the function pointer, you can use the dereference operator *:
int result = (*function_ptr)(10, 20); // result = 30
- Alternatively, you can use the function name without the dereference operator:
int result = function_ptr(10, 20); // result = 30
- Function pointers can be passed as arguments to other functions, just like any other pointer type. For example:
void invoke_function(int (*func)(int, int)) {
int result = func(10, 20);
printf(“Result: %d\n”, result);
}
int main() {
invoke_function(&add); // prints “Result: 30”
return 0;
}
- Function pointers can also be used as callback functions. For example, you can define a function that takes a function pointer as an argument and invokes the function when certain conditions are met.
void invoke_callback(int (*callback)(int), int x) {
if (x > 10) {
callback(x);
}
}
int main() {
void (*callback)(int) = &print_number;
invoke_callback(callback, 15); // prints “15”
return 0;
}
