Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums to Array bindings

Is it ok to have tight binding between Enums to their correspoind Arrays

Please note these are just pseudo code to just get an understanding.

Method 1. One way is we create the declare and define the array.

enum Names
{
    ABC,
    DEF,
    GHI
};

char* names[] = {"abc", "def", "ghl"};      // Declare and define.

To get the value we will do

char *nm = names[ABC];

This method has the drawback that we need to keep the enum and the names array in sync i.e if we change the enum that we move certain values those needs to be done in the table as well

For Ex: Move DEF to the top of the enum

enun Names { DEF, ABC, GHI };

// Change array as well.

char* names[] = {"def", "abc", "ghi"}

Method 2.

One way to break the binding between the enum and array is to have a create function like below.

int CreateNamesArray() {

      Names[GHI] = "ghl";

      Names[DEF] = "def";

      Names[GHI] = "ghi";

};

With this now even if the enum undergo change the array does not get impacted. One drawback for this approach is we need to call the function before we access the table.

Please suggest which approach is better. The tables would be some 30-100 entries.

like image 695
nakago Avatar asked May 09 '26 16:05

nakago


1 Answers

You can use macros to generate them:

#define LIST \
    PAIR(ABC, "abc") \
    PAIR(DEF, "def") \
    PAIR(GHI, "ghi")

#define PAIR(key, value) key,
enum Names { LIST };
#undef PAIR

#define PAIR(key, value) value,
char* names[] = { LIST };
#undef PAIR

#undef LIST

Change the pairs inside of LIST to set the key/value pairs.

like image 108
Pubby Avatar answered May 12 '26 06:05

Pubby