Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 407

15


Declaring a Pointer to a Function ................................................................

As with all C variables, you must declare a pointer to a function before using it. The gen-
eral form of the declaration is as follows:
type(*ptr_to_func)(parameter_list);
This statement declares ptr_to_funcas a pointer to a function that returns typeand is
passed the parameters in parameter_list. Here are some more concrete examples:
int (*func1)(int x);
void (*func2)(double y, double z);
char (*func3)(char *p[]);
void (*func4)();
The first line declares func1as a pointer to a function that takes one type intargument
and returns a type int. The second line declares func2as a pointer to a function that
takes two type doublearguments and has a voidreturn type (no return value). The third
line declares func3as a pointer to a function that takes an array of pointers to type char
as its argument and returns a type char. The final line declares func4as a pointer to a
function that doesn’t take any arguments and has a voidreturn type.
Why do you need parentheses around the pointer name? Why can’t you write, for the
first example:
int *func1(int x);
The reason has to do with the precedence of the indirection operator,*. It has a relatively
low precedence, lower than the parentheses surrounding the parameter list. The declara-
tion just given, without the first set of parentheses, declares func1as a function that
returns a pointer to type int. (Functions that return pointers are covered on Day 18,
“Getting More from Functions.”) When you declare a pointer to a function, always
remember to include a set of parentheses around the pointer name and indirection opera-
tor, or you will get into trouble.

Initializing and Using a Pointer to a Function ..............................................

A pointer to a function must not only be declared, but also initialized to point to some-
thing. That “something” is, of course, a function. There’s nothing special about a func-
tion that gets pointed to. The only requirement is that its return type and parameter list
match the return type and parameter list of the pointer declaration. For example, the fol-
lowing code declares and defines a function and a pointer to that function:

25 448201x-CH15 8/13/02 11:13 AM Page 407

Free download pdf