2

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);
}
Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
APoorDev
  • 171
  • 1
  • 11
  • In my opinion, function pointers inside a struct are more common and clearer: https://stackoverflow.com/questions/15612488/what-good-is-a-function-pointer-inside-a-struct-in-c – Jose Jan 04 '19 at 13:36

2 Answers2

6

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);
}
dbush
  • 205,898
  • 23
  • 218
  • 273
0

I usually find that the first step when dealing with a function pointer is to use a typedef to make the syntax more readable. Then, such pointers can be used much like any other data type.

// declares function_ptr as a new type, pointer to function taking an integer parameter and returning void
typedef void (*function_ptr)(int);

// define function pointer p and initialize to point at function one
function_ptr p = function_one;

// call function_one passing 7 as a parameter
(*p)(7);

In this case, assuming that all of the functions take an integer as a parameter, we can use a table of pointers to represent all the functions you'd want to call:

function_ptr table[]=
{
    function_one,
    function_two,
    function_three,
    function_four,
};

At this point it's fairly easy to call any number of functions using this method.

void call_functions(struct_t action, int exemple)
{
    if( action >= FUNCTION_ONE && action <= FUNCTION_FOUR )
    {
        (table[action])(exemple);
    }
    else
    {
        printf("Unrecognized function %i. Check that function table is up to date\n", (int)action);
    }
}
Tim Randall
  • 4,040
  • 1
  • 17
  • 39