From the perspective of the name, the function pointer knows that it is also a pointer, a pointer pointing to the function entry address. Let's take a simple example to see the usage of the function pointer.
1. Call a function through a function pointer.
[Cpp] # include <stdio. h>
# Include <stdlib. h>
Int Sum (int a, int B)
{
Return a + B;
}
Int Sub (int a, int B)
{
Return a-B;
}
Int main (int argc, char * argv [])
{
Int iTmp = 0;
Int (* pf) (int, int);/* declares a function pointer with two Integer Parameters and returns an integer */
Pf = Sum;/* assign a value to the function pointer to Sum */
ITmp = pf (20, 10);/* call */
Printf ("Sum is: % d \ n", iTmp );
Pf = Sub;/* point it to the Sub function */
ITmp = pf (20, 10);/* call */
Printf ("Sub is: % d \ n", iTmp );
System ("PAUSE ");
Return 0;
}
# Include <stdio. h>
# Include <stdlib. h>
Int Sum (int a, int B)
{
Return a + B;
}
Int Sub (int a, int B)
{
Return a-B;
}
Int main (int argc, char * argv [])
{
Int iTmp = 0;
Int (* pf) (int, int);/* declares a function pointer with two Integer Parameters and returns an integer */
Pf = Sum;/* assign a value to the function pointer to Sum */
ITmp = pf (20, 10);/* call */
Printf ("Sum is: % d \ n", iTmp );
Pf = Sub;/* point it to the Sub function */
ITmp = pf (20, 10);/* call */
Printf ("Sub is: % d \ n", iTmp );
System ("PAUSE ");
Return 0;
}
Running result:
[Plain]
Sum is: 30
Sub is: 10
Press any key to continue...
Sum is: 30
Sub is: 10
Press any key to continue...
2. The function pointer is used as a parameter of another function.
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
Int Sum (int a, int B)
{
Return a + B;
}
Int Sub (int a, int B)
{
Return a-B;
}
/* Define the function pointer type */
Typedef int (* pfFun) (int, int );
/* Functions with function pointer parameters */
Int TestFun (int a, int B, pfFun pf)
{
Int I = 0;
I = pf (a, B );
Return I;
}
Int main (int argc, char * argv [])
{
Int iTmp = 0;
ITmp = TestFun (20, 10, Sum);/* assign a value to the function Sum */
Printf ("Tmp is: % d \ n", iTmp );
ITmp = TestFun (20, 10, Sub);/* function pointer value: Sub */
Printf ("Tmp is: % d \ n", iTmp );
System ("PAUSE ");
Return 0;
}
# Include <stdio. h>
# Include <stdlib. h>
Int Sum (int a, int B)
{
Return a + B;
}
Int Sub (int a, int B)
{
Return a-B;
}
/* Define the function pointer type */
Typedef int (* pfFun) (int, int );
/* Functions with function pointer parameters */
Int TestFun (int a, int B, pfFun pf)
{
Int I = 0;
I = pf (a, B );
Return I;
}
Int main (int argc, char * argv [])
{
Int iTmp = 0;
ITmp = TestFun (20, 10, Sum);/* assign a value to the function Sum */
Printf ("Tmp is: % d \ n", iTmp );
ITmp = TestFun (20, 10, Sub);/* function pointer value: Sub */
Printf ("Tmp is: % d \ n", iTmp );
System ("PAUSE ");
Return 0;
} Running result:
[Plain]
Tmp is: 30
Tmp is: 10
Press any key to continue...
Tmp is: 30
Tmp is: 10
Press any key to continue...
The second usage is the legendary callback function.
From Socrates Column