The following essay explains the usage of function pointers.
Definition of function pointer:
Definition form:
Storage type data type (* function pointer name) ()
meaning:
The function pointer points to the program code storage area
Typical use of function pointer —– implement function callback
Function called through function pointer
For example, the pointer of a function is passed to a function as a parameter, so that different methods can be used flexibly when dealing with similar events.
The caller doesn’t care who the caller is
The existence of a specific prototype and the need to know the existence of a function.
Function pointer example
1 #include
2
3 using namespace std;
4
5 int compute(int a, int b, int(* func)(int, int))
6 {
7 return func(a, b);
8 }
9
10 int max (int a, int b) // find the maximum value
11 {
12 return ((a > b) ? a : b);
13 }
14
15 int min (int a, int b) // find the minimum value
16 {
17 return ((a < b) ? a : b);
18 }
19
20 int sum (int a, int b) // sum
21 {
22 return (a + b);
23 }
24
25 int main(void)
26 {
27 int a, b, res;
28
29 cout << "please input integer a:";
30 cin >> a;
31
32 cout << "please input integer b:";
33 cin >> b;
34
35 res = compute(a, b, &max); // You can also enter max, which also represents the address
36
37 res = compute(a, b, &min); // You can also enter min, which also represents the address
38
39 res = compute(a, b, &sum); // You can also enter sum, which also represents the address
40
41 return 0;
42 }
This article is connected to: https://www.cnblogs.com/iFrank/p/14444636.html