C++ function as parameter

In C++ you can have a function (many also possible) as a parameter of another function. In the example below, function sum is passed to the avg() function to calculate the average of the values in array. The function sum will be called from the avg function. To accept function type parameter, in avg, you must declare the parameter as a function pointer. This function pointer must be compatible to the function sum. I mean the function pointer must have data type, and parameters as the sum function.
-Function Pointer: int (*f)(int [])
   +data type: int
   +parameter: an integer array

-Function sum: int sum(int a[])
   +data type: int
   +parameter: an integer array

#include <cstdlib>
#include <iostream>
using namespace std;

int size;// size of array
//sum function body calculating total
int sum(int a[]){
   int s=0;
   size=sizeof(a);
   for(int i=0;i<size;i++)
        s+=a[i];
   return s;
}
//avg function body calculating average
//avg function has one parameter that is a function
double avg(int (*f)(int[]),int arr[]){
  
   double av=f(arr)/(double)size;
   return av;
}



int main(int argc, char *argv[])
{
  
   int arr[]={12,12,12,5};
   cout<<avg(sum,arr)<<"\n"; //pass sum function as parameter value
   system("PAUSE");
   return EXIT_SUCCESS;
}

Posted by: Dara | post date: 02-03-2013 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.