Search code examples
arrayscfunction-pointersdeclaration

write a variable that takes a list of functions


I want to write a variable that takes a list of functions, is that even possible? to have a list of functions in C?

example:

// this type is for one function
void (*f)(void) = func1;

// but this is what I need
/*TYPE*/ vf = { func1, func2, NULL };

I dont want to build new struct that hold the function and the next function, I want to like i mentioned above, is that possible without creating a dedicated struct?

note: I am not bound to a specific C standard


Solution

  • This record

    void (*f)(void) = func1;
    

    declares one pointer to function.

    This record

    void ( * vf[] )( void ) = { func1, func2, NULL };
    

    or

    void ( * vf[3] )( void ) = { func1, func2, NULL };
    

    declares an array of pointers to functions.

    You could simplify the declaration using a typedef either for the function type or for a pointer to the function type as for example

    typedef void Func( void );
    Func * vf[3] = { func1, func2, NULL };
    

    or

    typedef void ( *FuncPtr )( void );
    FuncPtr vf[3] = { func1, func2, NULL };