Home > Article > Backend Development > How do function pointers work in C++?
In C++, a function pointer is a variable pointing to a function, which can dynamically pass or store the function as a parameter. The syntax is: type name * function name. When allocating, use the function pointer address and dereference it when calling. For example, when calculating the maximum value using a function pointer, the calculation is performed by allocating the function pointer and calling it.
In C++, a function pointer is a variable that points to a function. It allows us to dynamically pass functions as parameters or store them in data structures.
The function pointer is declared like a regular function, but the type name is followed by an asterisk (*):
typedef void (*FunctionPointer)(int);
We can do it like Assign a function address to a function pointer like an ordinary pointer:
FunctionPointer fp = &myFunction;
We can call it by dereferencing the function pointer:
fp(10);
Let's consider a program that uses function pointers to calculate the maximum of two numbers:
#include <iostream> using namespace std; // 最大值函数 int max(int a, int b) { return a > b ? a : b; } // 函数指针比较函数 int compare(int a, int b, int (*fp)(int, int)) { return fp(a, b); } int main() { // 分配函数指针并调用它来计算两数的最大值 int (*fp)(int, int) = &max; int result = compare(5, 10, fp); // 打印结果 cout << "最大值:" << result << endl; return 0; }
The above is the detailed content of How do function pointers work in C++?. For more information, please follow other related articles on the PHP Chinese website!