Search code examples
cpointersstructure

Functions pointers


Hey guys I have a question: How can i call a function from an enum structure with pointers?

For example I have this structure:

typedef enum struct_e
{
    FUNCTION_ONE,
    FUNCTION_TWO,
    FUNCTION_THREE,
    FUNCTION_FOUR,
}   sctruct_t;

And I have a function that receives one of these variables and the parameters of the function (for example an int)

void call_functions(struct_t action, int exemple) {...}
// -> call like this call_functions(FUNCTION_ONE, 45);

And in that function I have to call one of the functions like this one:

void function_one(int a)
{
    printf("You have %d years old", a);
}

Solution

  • Assuming each of the functions to call has type void (*)(int), you can create an array of function pointers, using the enum values as the array index:

    typedef void (*call_func_type)(int);
    call_func_type func_list[] = {
        [FUNCTION_ONE] = function_one,
        [FUNCTION_TWO] = function_two,
        [FUNCTION_THREE] = function_three,
        [FUNCTION_FOUR] = function_four
    }
    

    Then call_functions would just index into that array:

    void call_functions(struct_t action, int example) 
    {
        func_list[action](example);
    }