Since the function also occupies the storage space in the memory, it also has a starting address, so you can also use a pointer to point to the function starting address, that is, you can use the pointer to call the corresponding function.
.Function pointer definition
Format: 存储类型 数据类型 (*函数指针名)()
Note 1: The brackets between * and the function name are indispensable, otherwise it will become a pointer to the function (that is, a function that returns a pointer type)
Note 2: The function type must match the call to be called Function type, the function parameter list should match the function parameter list that is called. Such as:
int max(int a,int b);
int min(int a,int b);
int (*fun)(int a,int b);
Meaning The
function pointer points to the program code storage area
The typical use of function pointers-to implement function callbacks
. Functions called by function pointers.
For example, passing a function pointer to a function allows different methods to be used flexibly when dealing with similar events.
.The caller does not care who is the victim. It
needs to know that there is a called function with a specific prototype and restrictions.
Example:
#include <iostream>
using namespace std;
int compute(int a,int b,int (*func)(int,int))
{
return func(a, b);
}
int max(int a,int b)
{
return ((a > b) ? a : b);
}
int min(int a, int b)
{
return ((a < b) ? a : b);
}
int sum(int a, int b)
{
return a+b;
}
int main()
{
cout<<compute(1, 10, max)<<endl;
cout << compute(1, 10, min) << endl;
cout << compute(1, 10, sum) << endl;
}
//结果为10 1 11