1

I don't quite understand the purpose of this. I have searched and read what seems to be the same thing on different sources, but none of them give an explanation as to what it does specifically and what is it's purpose.

can anyone help me understand this

1
  • You use function pointers basically when you don't know before hand what function you want to call.
    – pmg
    Jun 8, 2011 at 8:17

5 Answers 5

3

Let's take a look in the Standard C library:

void qsort(void *BASE, size_t NMEMB, size_t SIZE, 
    int (*COMPAR)(const void *, const void *) );

the last argument of qsort is pointer to compare function. the compare function is used to compare two elements from the array (it defines the ordering). If qsort() wouldn't be using function pointer we would have to write over and over again qsort() if we have different ordering requirement or new types/struct we would like to sort.

1
  • 1
    Basically, Op's example shows that function pointers allow functions to be passed as arguments.
    – user456814
    Jun 8, 2011 at 7:49
3

Take the following:

int i = 10;

A corresponding pointer can be defined like this:

int* p = &i;

Variable "p" is very similar to "i", in that they are both numbers. However, the value of 'p' is the memory address of variable 'i', in other words, it is the exact memory address where value 10 is stored. Furthermore, 'p' knows the type of the value at that memory address. It knows it is an "int", since it was defined as "int" + "star".

Similarly, consider a function:

int m(char* arg1, double arg2)
{
    /* do something */
}

C provides the ability to access the memory address of where this function is stored. A function is not like a value, e.g. it cannot be changed, so when one says the memory address of a function, this actually means the memory address where the code of the function is located, e.g. whatever is written between the curly braces.

However, there is a similarity between a function and a variable. They both have a type. A function's type is comprised of:

  1. Return Type
  2. Parameter Type List, namely:
    1. Type of parameter #1
    2. Type of parameter #2
    3. ...
    4. Type of parameter #N

C treats all functions that have the same return type and parameter type lists as "the same type of function". Similar to how two variables declared as "int i,j" are considered to be the same type, so are two functions with the same signature considered the same type.

The syntax for describing the type of a function includes the bare minimum: the return type and the types of each parameter (in the right order):

return-type (* <variable-name>)(Type-of-Param-1, Type-of-Param-2, ..., Type-of-Param-N)

In effect, in order to declare a pointer to function 'm' above:

int (*p)(char*, double) = &m;

"int" is the return type of method 'm', the fir pair of round brackets and the star are part of the syntax, 'p' is the variable name, "char*" is the type of the first parameter, and "double" is the tyep of the second parameter. There is no reference to the parameter names -- as the names of the parameters are not relevant to the type/signature of a function.

Note that similar to a variable, the address of a method is obtained exactly the same as for a variable, i.e. by prepending it with an ampersand.

Pointers to functions can be passed around simlar to pointers to variables, and more importantly, the code of the function at that particular memory address can be invoked. For example, in order to invoke function 'm' by means of pointer 'p', it would take something like this:

int result = p(NULL, 10.0);
int result = (*p) (NULL, 10.0); // alternative syntax
2

The typical example is a sorting function that needs you to "point" it to a function that can compare two elements. You pass this function a pointer to your comparison function so that it can call your function when it needs to do a comparison. You can't actually pass the function, but you can pass it a pointer to a function, which is just a variable that "points" to where your function is in memory. The sorting function can call your function by using this pointer. Pointers, in general, are just variables that store a memory address. That memory address is what it's "pointing" to, and it can be anything at that address - a function, an integer, a series of character variables that end with a null character. Function pointers are just variables that store the memory address of where a function is in memory so that the function can be called by some other piece of code.

Hope that explanation helps.

1
  • This example shows that function pointers allow functions to be passed as arguments to other functions, nice example.
    – user456814
    Jun 8, 2011 at 7:50
0

It is no more simple then this.

When you know how and why pointers work with normal variables, think of using these pointers, but this time with functions. That is, you replace the address of variables now with the address of the function, with all the power of pointers there, you can now access function indirectly by using the pointers that point to them instead of using their names directly.

From http://www.cplusplus.com/doc/tutorial/pointers/

// my first pointer
#include <iostream>
using namespace std;

int main ()
{
  int firstvalue, secondvalue;
  int * mypointer;

  mypointer = &firstvalue;
  *mypointer = 10;
  mypointer = &secondvalue;
  *mypointer = 20;
  cout << "firstvalue is " << firstvalue << endl;
  cout << "secondvalue is " << secondvalue << endl;
  return 0;
}

And the output for the above is

firstvalue is 10
secondvalue is 20

Now from http://www.newty.de/fpt/intro.html#what We have function pointers.

//------------------------------------------------------------------------------------
// 1.2 Introductory Example or How to Replace a Switch-Statement
// Task: Perform one of the four basic arithmetic operations specified by the
//       characters '+', '-', '*' or '/'.


// The four arithmetic operations ... one of these functions is selected
// at runtime with a swicth or a function pointer
float Plus    (float a, float b) { return a+b; }
float Minus   (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide  (float a, float b) { return a/b; }


// Solution with a switch-statement - <opCode> specifies which operation to execute
void Switch(float a, float b, char opCode)
{
   float result;

   // execute operation
   switch(opCode)
   {
      case '+' : result = Plus     (a, b); break;
      case '-' : result = Minus    (a, b); break;
      case '*' : result = Multiply (a, b); break;
      case '/' : result = Divide   (a, b); break;
   }

   cout << "Switch: 2+5=" << result << endl;         // display result
}


// Solution with a function pointer - <pt2Func> is a function pointer and points to
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
   float result = pt2Func(a, b);    // call using function pointer

   cout << "Switch replaced by function pointer: 2-5=";  // display result
   cout << result << endl;
}


// Execute example code
void Replace_A_Switch()
{
   cout << endl << "Executing function 'Replace_A_Switch'" << endl;

   Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');
   Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}

As you will see from the above call, the address of Minus() function is passed which is then in passed on to call the actual function via pointer and in this case, pt2Func(...). Note that in the case of function pointers you will take care of the function signature as well.

  • float (*pt2Func)(float, float)
  • float Minus (float a, float b) { return a-b; }

As you can see above, the signatures are the same, so you can pass in any function address and the call will work.

I hope this helps.

5
  • @Paul, its not my fault, SO is not showing the formatting buttons or my explorer has gone bad!
    – user349026
    Jun 8, 2011 at 7:52
  • @Wajih: code formatting seems to work OK for everyone else. Anyway, no one wants to read a bunch of unformatted code, especially when that code has just been copied and pasted from elsewhere - you might as well just post a link. Also note that the question is tagged C but your code examples are C++.
    – Paul R
    Jun 8, 2011 at 7:54
  • 1
    pasting only a link would be much more useful and much less intrusive Jun 8, 2011 at 7:58
  • @OK guys, buttons worked again so reformatted. I could not do summarizing as it would loose the essence of explanation.
    – user349026
    Jun 8, 2011 at 7:58
  • @Op De, I don't think so, the guy said he had looked at different resources, so that is why an explanation would be reasonable. So the length answer.
    – user349026
    Jun 8, 2011 at 8:01
0

Function pointers are used to dynamicly call functions. You could for example take a function pointer as an argument to another function and in a sense provide additional functionality in that way. You could also create structs that have function pointers and thus a sort of member functions, like for classes. This could be usefull if you have a function that works on your structs but they can be a bit different in what work should actually be done with them. For example:

// Structures for our "objects"
typedef int funcPtr();

struct foo {
  int a;
  int b;
  funcPtr* run;
}

struct bar {
  int a;
  int b;
  funcPtr* run;
  char* s;
}

// Functions that we will use as our "member functions"
int runOne() {
  return 1;
}

int runTwo() {
  return 2;
}

// Functions to create objects... kinda like new operators
struct foo* NewFoo(int aVal, int bVal) {
  struct foo* this = (stuct foo*)malloc(sizeof(struct foo));
  this->a = aVal;
  this->b = bVal;
  this->run = runOne;
  return this;
}

struct bar* NewBar(int aVal, int bVal) {
  struct bar* this = (stuct bar*)malloc(sizeof(struct bar));
  this->a = aVal;
  this->b = bVal;
  this->run = runTwo;
  return this;
}

// Create "objects"
struct foo* myFoo = NewFoo(10, 20);
struct bar* myBar = NewBar(30, 40);

// Run the run function on them (which actually runs different functions for each "object")
int result1 = myFoo->run();
int result2 = myBar->run();

result1 will now be 1 and result2 will be 2. This can be used if you have structs containing different kinds of "modules" with a similar interface but with different behavior for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.