manish ma
manish ma

Reputation: 2038

Add suffix to enum during runtime

I want a function to accept an enum string and add a suffix to that string, essentially convert that into a define string.

ACTION_PERMIT ---> ACTION_PERMIT_F

Is there a way to do this? Or is there a better way to perform this mapping?

typedef enum {
    ACTION_PERMIT,    
    ACTION_DENY,      
    ACTION_COUNT,     
    ACTION_TC,        
    ACTION_REDIRECT  
}action_e;

#define    ACTION_PERMIT_F        1 << 0     
#define    ACTION_DENY_F          1 << 1     
#define    ACTION_COUNT_F         1 << 2     
#define    ACTION_TC_F            1 << 3     
#define    ACTION_REDIRECT_F      1 << 4  


void rule_action_add(rule *rule, action_e action_type, uint32 value)
{
    assert(rule != NULL);
    action_t *action = &rule->action;

    action->exist_map |= action_type;   // <--- Use enum string and add "_F" suffix   
}

Upvotes: 1

Views: 100

Answers (1)

user694733
user694733

Reputation: 16043

Is there a way to do this?

Not like this. Value of action_type variable exists at runtime, and by that point preprocessor has already ran.

Or is there a better way to perform this mapping?

You can use the numeric value of the enumeration constant for the bit shift.

action->exist_map |= (1u << action_type);

Upvotes: 2

Related Questions