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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With