Sunday, August 26, 2007

How to read C declarators PART 2

Function pointers and combinations

The C "forward" declaration:

 1.) extern int foo();

just says that foo is a function returning int. This follows the same pattern for reading declarators as you saw in previous post. Start at foo and look right. You see () so say function. You look left and see int. Say int.

        2.) extern int *foo();

Yep, you say foo is a function returning a pointer to int.

Now for the big leap. Just like we can make a pointer to an int or whatever, let's make a pointer to a function. In this case, we can drop the extern as it's no longer a function forward reference, but a data variable declaration. Here is the basic pattern for function pointer:

 3.) int (*foo)();

You start at foo and see nothing to the right. So, to the left, you say pointer. Then to the right outside you see function. Then left you see int. So you say foo is a pointer to a function returning int.

Here is an array of pointers to functions returning int:

 4.) int (*Object_vtable[])();

One last, incredibly bizarre declaration, for fun:

 5.) int (*(*vtable)[])();

This pointer to a vtable is set to the address of a vtable.

In summary:

 int *ptr_to_int;
int *func_returning_ptr_to_int();
int (*ptr_to_func_returning_int)();
int (*array_of_ptr_to_func_returning_int[])();
int (*(*ptr_to_an_array_of_ptr_to_func_returning_int)[])();

regards
Al

No comments: