Example of a function pointer -- int (* FunctionFound (char op) (int, int);, -- intfunctionfound
This Code demonstrates the example of a function pointer. In windows, the gcc command is used to compile the pointer;
/*******************************************
* this file is to test function pointer
*
*******************************************/
#include <stdio.h>
Typedef int(*FP_CALL)(int,int); //Defines a function pointer type
Int (*data_return)(int); // Defines a function pointer of global type
Int DataReturn(int a)
{
Return a;
}
Int AddCaculate(int a, int b)
{
Return (a + b);
}
FP_CALL CallFunction(char op)
{
Switch(op)
{
Case '+' :
Printf("found the function AddCaculate \n");
Return AddCaculate;
Break;
Default :
Printf("the input error\n");
}
}
Int (* FunctionFound(char op))(int , int) // this is a function whose return data is a function pointer;
{
Return CallFunction(op);
}
Void main()
{
FP_CALL function_call;
Int *p;
Int a = 100;
Data_return = DataReturn;
p = &a;
Function_call = FunctionFound('+');
Printf("hello my honey!!!\n");
Printf("the function pointer data_return address is : %d \n",data_return);
Printf("the function pointer *data_return address is : %d \n",*data_return);
Printf("the (*data_return)(2) result is : %d .\n",(*data_return)(2));
Printf("the data_return(3) result is : %d .\n",data_return(3));
Printf("the int pointer (*p) is : %d \n",*p);
Printf("the int pointer p is : %d \n",p);
Printf("the function_call run result is :%d \n", function_call(10,12));
/* */
}
Running result:
Analysis: 1. typedef int (* FP_CALL) (int, int); // defines a function pointer type, not a function pointer; FP_CALL function_call; // This sentence defines a function pointer; 2. int (* data_return) (int); // This is to define a function pointer directly; and in 1, the definition method is different. 3. FP_CALL CallFunction (char op) // the return value of this function is a function pointer. 4. int (* FunctionFound (char op) (int, int) // The return value of this function is also a function pointer. This function pointer has two int parameters and the return value type is int. 5. The addresses defined by data_return and * data_return are the same; that is to say, data_return (2); and (* data_return) (2); can call the function pointed to by the function pointer;