Saturday, July 23, 2011

Pointer to Function in C/C++


A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.
The type of a pointer to a function is based on both the return type and parameter types of the function.


A declaration of a pointer to a function must have the pointer name in parentheses. The function call operator () has a higher precedence than the dereference operator *. Without them, the compiler interprets the statement as a function that returns a pointer to a specified return type. For example:


int *f(int a); /* function f returning an int* */
int (*g)(int a); /* pointer g to a function returning an int */
char (*h)(int, int) /* function h that takes two integer parameters and returns char */


In the first declaration, f is interpreted as a function that takes an int as argument, and returns a pointer to an int. In the second declaration, g is interpreted as a pointer to a function that takes an int argument and that returns an int.

No comments:

Post a Comment