Search code examples
cenumsfunction-pointers

function pointers and enum in C


I am looking for a fancy way to link function pointers and enums.

In my case I have a message queue that holds a event id and some data associated with the event. some simple pseudo code:

event=(eid, data)
switch(eid) {
    case eid1:
        handler1(data);
        break;
    case edi2:
        handler2(data);
        break;

}

Now I like to do some optimization. If the event id has the value of the function called inside of the switch case statement I can save the switch case decode by preserving a nice readability of the code.

event=(eid, data)
eid(data)

Now if I am putting it into an example like:

static void abc(void * p) {

}

static void abc2(void * p) {

}

enum eventId {
    eid1 = abc,
    eid2 = abc2
} xyz;

My compiler tells:

error: enumerator value for 'eid1' is not an integer constant eid1 = abc

What is absolutely right.

Any ideas how to solve that problem?


Solution

  • Use an array of function pointers, and use the enum as the index.

    typedef void (*handler_func)(void *);
    handler_func event_handlers[] = { abc, abc2 };
    enum eventId {
        eid1 = 0,
        eid2 = 1,
        eid_max
    }
    
    if (eid < eid_max) event_handlers[eid](data);