Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› Pointers To Functions

Pointers To Functions

C Programming Tricks

Pointers to functions:

In C, pointers to functions are not used as much as they could be used. I am convinced that the primary reason for this is that nobody remembers the syntax for the declaration. The solution is simple: just look up an example in any decent book or self-respecting header file. After a couple of years -- you have memorized it!

For your convinience, I'll include an example here. If you have a function that takes an integer and returns a pointer, such as

 char * foo (int);
 then defining a corresponding function pointer type is easy -- just replace function name with (*varname): 
 
 char * (*fooptr) (int) = foo;
 

Note that parentheses are required; otherwise, instead of a declaration of a pointer to a function that returns a pointer you will get a declaration of a function that returns a pointer to a pointer, which is obviously not what you intended.

It is often handy to a define a function pointer type. This is done by puting typedef in front of the declaration the and substituting type name for variable name:

 typedef char * (*footype) (int);
 You can you use your type to declare variables, but not functions: 
 
 footype baz = foo; /* Ok */
 foo this_doesnt_work { return (NULL); } /* Can't do that */
 
 You can use function pointers to do many interesting things, some more 
 acceptable in production code than others. Example of the latter: you 
 can shorten the notation of 
 
 if (z) then x(a, b); else y(a, b);
 not only to 
 
 z ? x(a, b) : y(a, b);
 but further to 
 
 (z ? x : y) (a, b);
 

Partners