# Using a function pointer as a function argument

• 10-09-2010
evansm84
Using a function pointer as a function argument
Hello all,

I am trying to learn C++ on my spare time and am following the book "c++ primer plus" right now.. In one of the exercises I want to be able to use a function as one of the arguments to an other function. However, the function inside of the other functions arguments is not being called.. here is a piece of the code...

The prototype of the two functions:
Code:

```int average_score(int ar[], int limit); void display_scores(const int ar[], int limit, int (*avg_score)(int*, int));```
The function call:

Code:

`display_scores(golf_scores, num_of_scores, average_score);`
and the definitions:
Code:

```int average_score (int ar[], int limit) {         int average = 0;         int x;         for (x = 0; x < limit; x++)         {                 average = average + ar[x];         }         average = average / limit;         cout << "This is function average_score() " << endl ;         return average; }        void display_scores(const int ar[], int limit, int (*avg_score)(int*, int)) {         int x;         for (x = 0; x < limit; x++)         {                 cout << ar[x] << " ";         }         cout << endl << "The average score is " << avg_score << endl; }```
I know that it is not necessary to do it like this, but I would like to know why it doesn't work. I will attach the entire piece of code.. Thanks to anyone who can help me.. I worked on this problem for several hours tonight and could not figure it out.
• 10-09-2010
NeonBlack
That's because you're not calling the function:
Code:

`cout << endl << "The average score is " << avg_score << endl;`
You don't call a function with the name alone. You need to supply the arguments (or an empty set of parenthesis if there are none)
Try something like this:
Code:

`cout << endl << "The average score is " << avg_score(ar, limit) << endl;`
Function pointers are cool in C, but in C++, I would recommend using function objects which overload operator().
• 10-09-2010
Syscal
If you wanted that to be clearer:

Code:

```typedef int (*func)(int*, int); void display_scores(const int ar[], int limit, func avg_score){ }```
third parameter is typedef'd