Rajesh Rajesh - 1 year ago 59
C Question

Function Pointer declaration and function definition together

I saw some piece of code in one of the old files.

void (*const m_exec[N_EXECS])(void) =
#define PROCESS_DEF_TIMED(name) name, // defines macro for use in proclist.h
#define PROCESS_TIMED // define switch for section in proclist.h
#include "proclist.h"
#undef PROCESS_TIMED // undefine switch
#undef PROCESS_DEF_TIMED // undefines macro

I am unable to understand the meaning of this code. Is this a function pointer with declaration and function definition together? But if I try to declare similar function pointer like below, I get compilation error

void (*voidFptr)(void) =

Also what is #define here? Why this is inside the function I am not sure.

Answer Source


void (*const m_exec[N_EXECS])(void)

is the way you declare an array of function pointers in C. You are not alone in finding this difficult to read. It declares an array of length N_EXECS, where each element in the array is a function that takes no arguments and returns a pointer to a const-void.

The braces-enclosed block after it is the array initializer; probably proclist.h has a whole list of function pointer declarations in it, and this is essentially pasting those into this array. If you want to see what's actually happening after the #include, you can use the -E flag of your compiler. So if this were in main.c, you would run:

gcc -E -Ipath/to/headers -Iother/path/to/headers main.c

And it would give you a (probably huge) dump of source code, which is the result of pushing that file through the preprocessor and evaluating all of the #include statements.

Edit: missed your last question.

Probably (and this is conjecture without seeing proclist.h), the things its defining change the contents of proclist.h. For example, if it contained:


Then #define PROCESS_TIMED would change what ended up in your m_exec array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download