Calling functions with function pointer variables
Pointer variables can also point to a function. A function is assigned to an entry address at compile time. This function entry address is called a pointer to a function. You can point to a function with a pointer variable, and then call this function through the pointer variable.
Example of A and B in the big people.
First write the program in the usual way:
#include <iostream>
using namespace std;
int main ()
{
int max (int x,int y);//function declaration
int a,b,m;
cin>>a>>b;
M=max (A,B); Call function Max, find the maximum value, assign M
cout<< "max=" <<m<<endl;
return 0;
}
int max (int x,int y)
{
int z;
if (x>y) z=x;
else z=y;
return (z);
}
You can point to the Max function with a pointer variable, and then call this function through the pointer variable. The way to define pointer variables to the MAX function is:
Compare it to the prototype of the function Max:
int max (int, int); Max function prototype
As you can see, it's just replacing Max with (*P), all the same. Now modify the main function of the above program as follows:
#include <iostream>
using namespace std;
int main ()
{
int max (int x,int y);//function declaration
Int (*p) (int,int);//define pointer variable p
int a,b,m
pointing to function; P=max; Make P point to function Max
cin>>a>>b;
M=p (a,b);
cout<<″max=″<<m<<endl;
return 0;
}
Note that the assignment statement "P=MAX;" On line 7th. This statement must not be omitted, it is to assign the function Max's entry address to the pointer variable p. At this point, p only points to function max.
The general definition of a pointer variable that points to a function is:
function type (* pointer variable name) (function parameter list);
C + + function to return pointer values
A function can bring back an integer value, a character value, a real value, and so on, or it can bring back the pointer type of data, that is, the address. The concept is similar to the previous one, except that the type of the value returned is the pointer type. A function that returns a pointer value is simply a pointer function.
The general form of defining a pointer function is:
Type name * Function name (parameter table column);
For example: