Chapter 05 Compound Data Type - Constructed Type
5.5 Pointer for a Function
-
Definition
<return-type> (*<pointer>) (<parameter-list>); //or typedef <return-type> (*<type-name>) (<parameter-list>); <type-name> <pointer>;
-
Call using a Pointer
(*<function-pointer>)(<argument-list>); //or <function-pointer>(<argument-list>);
-
Assignment
fp = &f; //we can use & to get the address of a function //or fp = f; //the compiler will convert the name of a function into an address implicitly
Example:
#include <iostream>
#include <cmath>
using namespace std;
const int MAX_LEN = 8;
typedef double (*FP) (double);
FP func_list[MAX_LEN] = {sin, cos, tan, asin, acos, atan, log, log10};
int main(){
int index;
double x;
do{
cout << "Please input the function you want to compute (0:sin 1:cos 2:tan 3:asin" << endl;
cout << "4:acos 5:atan 6:log 7:log10):";
cin >> index;
} while (index < 0 || index > 7);
cout << "Please input the argument:";
cin >> x;
cout << "The outcome is:" << (*func_list[index])(x) << endl;
return 0;
}
- Pass a function to another function
Juse refer to the higher-order function we’ve learnt in Python, and combine it with call-by-reference, you will understand the working principle for the functional pointer passing a function. The following example will show the process.
#include <iostream>
#include <cmath>
using namespace std;
const int N = 1e6;
double Integrate(double (*pfun)(double x), double x1, double x2) {
double s = 0;
int i = 1, n;
while(i <= n){
s += (*pfun)(x1 + (x2 - x1) / n * i);
++i;
}
s *= (x2 - x1) / n;
return s;
}
double square(double x){
return x * x;
}
int main(){
cout << Integrate(cos, 1, 2) << endl;
cout << Integrate([](double x)->double {return x * x}, 0, 1) << endl; //lambda expression for anonymous function
cout << Integrate(square, 0, 1) << endl;
return 0;
}
Since we’ve make it clear that pointer is also a kind of data type, it is stored in the memory with a unique address, which indicates that we can use anothor pointer to point at it and use the third pointer to point at this one. As a result, we will get higher-order pointer.