Function Pointers, part 1 - Function Pointer as Argument and Return Value
(Page 3 of 4 )
Passing a function pointer as an argument to a function is quite essential when you want to implement callback functions. Although we won’t be looking at the implementation and usage of callback functions until later on, let’s take a look at the syntax right now.
The benefit of passing a function pointer as an argument to another function lies in the fact that this allows us to dictate which function that other function has to execute. There is nothing really different from what we have seen before, except for the fact that it looks slightly different.
// a raw declaration
void foo(int (*FPtr)(char const*));
// using a typedef
typedef int (*FuncPtr)(char const*);
void foo(FuncPtr fptr);
Did you recognize the function passed in through a pointer to foo? It is a function that takes a char const pointer as an argument and returns an int.
int func(char const *param);
Another tricky syntax is the raw declaration of a function that returns a function pointer.
// a raw declaration
int (*getFuncPtr1(int ID))(char const*);
// using a typedef
typedef int (*FuncPtr)(char const*);
FuncPtr getFuncPtr2(int ID);
It is pretty clear that the usage of a typedef clears things up a lot in this case. Did you notice that getFuncPtr1 returns a pointer to the same function (func) we had actually already declared before?
Function Pointer Arrays Since they are stored as variables, it is possible to have an array of function pointers -- but mixing the two guarantees a confusing syntax when you are going to do it all "raw." The beauty of function pointer arrays comes from the fact that you can bind functions to indices, which in turn could come from an enumeration you declared earlier on. This way you can create statements like: int res = (*opArray[PLUS])(a,b);.
// a raw declaration
int (*funcArray1[10])(char const*);
// using a typedef
typedef int (*FuncPtr)(char const*);
FuncPtr funcArray2[10];
// an example assignment
funcArray1[0] = funcArray2[5] = &func;
// example usage
int result1 = (*funcArray1[0])(“a test”);
int result2 = (*funcArray2[5])(“and then some”);
Next: Defining and Using Pointers to Templated Functions >>
More C++ Articles
More By J. Nakamura