Software & Finance





C++ - Function Pointers





The following is the sample declaration for function pointer that takes two integers as input and returns an integer value.

 

int (*fp1)(int, int);

 

 

The following is the sample declaration for a function that takes function pointer as an argument.

 

int PassFuncPtr(int (*fp)(int, int));

 

 

The following is the definition of the above function declaration. It simply calls the function with the hard coded values of 10 and 20.

 


Source Code


int PassFuncPtr(int (*fp)(int, int))

{

return fp(10, 20);

}

  

int addition(int a, int b)

{

return a+b;

}

 

int _tmain(int argc, _TCHAR* argv[])

{

int (*fp1)(int, int);

fp1 = addition;

 

int value = PassFuncPtr(addition); // we can also pass fp1 here

std::cout << value;

}

Output


30