Functions are stored in the code area of memory, they also have an address, how can we get the address of the function?
If we have a function of int test (int a), then its address is the name of the function, which is like an array, whose name is the starting address of the array.
Define a pointer to a function in the following form, using the above test () as an example:
Int (*FP) (int a);//This defines a pointer to a function
Function pointers cannot absolutely point to different types, or functions with different parameters, and we can easily make the following error when defining function pointers.
int *FP (int a);//This is the wrong thing to do, because in terms of binding and precedence, it's a function of returning the shape pointer, not a function pointer.
Let's take a look at a specific example:
#include <iostream>
#include <string>
using namespace Std;
int test (int a);
void Main (int argc,char* argv[])
{
cout<<test<<endl;//Display function Address
Int (*FP) (int a);
fp=test;//assigns the address of the function test to the function pointer FP
COUT<<FP (5) << "|" << (*FP) <<endl;
The above output FP (5), which is the standard C + + notation, (*FP) (10) This is compatible with the C language standard writing, two agree, but pay attention to distinguish between the program to avoid a transplant problem!
Cin.get ();
}
int test (int a)
{
return A;
}
A typedef definition simplifies the definition of a function pointer, does not feel when you define one, but is easier to define, and the code above is rewritten in the following form:
#include <iostream>
#include <string>
using namespace Std;
int test (int a);
void Main (int argc,char* argv[])
{
cout<<test<<endl;
typedef int (*FP) (int a);//Note that this is not a life function pointer, but rather a type that defines a function pointer, which is defined by itself, and the type named FP
FP fpi;//here uses its own defined type name FP to define a FPI function pointer!
Fpi=test;
COUT<<FPI (5) << "|" << (*FPI) <<endl;
Cin.get ();
}
int test (int a)
{
return A;
}
The function pointer can also be passed as a parameter to the function, let's look at an example, read carefully you will find it useful, a little reasoning can be very convenient for us to do some complex programming work.