What is the purpose and usage of function pointers in the C language?
A function pointer is a pointer variable that points to a function, which can be used to store the address of a function. The purpose and usage of function pointers are as follows:
- Effect:
- Functions can be passed between functions and used as parameters in another function, achieving callback functions.
- Dynamic function invocation can be achieved, where different functions are called based on different conditions.
- Function polymorphism can be achieved by using function pointers to call different functions to achieve different functionalities.
- Usage:
- Declare a function pointer: return type (*pointer variable name)(parameter list)
- Assigning a function address: pointer variable name = function name or pointer variable name = &function name.
- To call a function through a function pointer:
(*pointer variable name)(parameter list) or pointer variable name (parameter list)
Example code:
#include <stdio.h>
void hello() {
printf("Hello, world!\n");
}
void goodbye() {
printf("Goodbye, world!\n");
}
int main() {
void (*funcPtr)();
funcPtr = hello;
funcPtr(); // 调用 hello 函数
funcPtr = goodbye;
funcPtr(); // 调用 goodbye 函数
return 0;
}
In this code snippet, a function pointer funcPtr is declared and assigned the addresses of the functions hello and goodbye. Finally, both functions are called by the function pointer.