Function Pointers

Declaring function pointers in C\C++ has a somewhat strange syntax, specially when you want to specify a function pointer as the return type of another function.
so here is a brief explanation:

To declare a pointer to an int called pNumber:

int *pNumber;

To declare a pointer to a function called pFunc (that has a string parameter and returns an int):

int (* pFunc)(string);

in red is the variable name, in purple is the type.

To declare a function that returns a pointer to a function:

int (* GetFuncPointer(void) )(string);

in red is a normal function declaration, in purple is the return type of that function.
S o basically int(*)(string) is the type of the function pointer.

If we want to declare a function that takes a function pointer as a parameter then we would write something like this:

void RegisterCallBack( int(*)(string) ); /* unnamed parameter */

or

void RegisterCallBack( int(*myCallback)(string) ); /* named parameter */

A prettier way to use function pointers is to use typedef to declare an alias. The typedef syntax is exactly the same as declaring a regular variable (or a function pointer).

typedef int(*FunctionPointer)(string);

now we can use FunctionPointer like this:

FunctionPointer GetFuncPointer(void);

Click For More Information…

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*