Detecting mismatched array <-> enum initializers
arrays, c, enums, initialization
Solution
What about a compile time assertion like the following? (Yes, there are more elaborate CT_ASSERT macros; this is to illustrate the idea.)
#define CT_ASSERT(expr, name) typedef char name[(expr)?1:-1]
enum {
ID_DOG = 0,
ID_SPIDER,
ID_WORM,
ID_COUNT
};
int const NumberOfEyes[] = {
2,
8,
0
};
CT_ASSERT (sizeof NumberOfEyes/sizeof *NumberOfEyes == ID_COUNT, foo);
Now when the `NumberOfEyes` array has more or less elements than `ID_COUNT`, this will cause an error along `x.c:15: error: size of array 'foo' is negative`. Negative array dimensions are a constraint violation that must be diagnosed by any C compiler out there.
Problem
When doing embedded programming with C, many times I find myself doing maps with enum and array because they are fast and memory efficient. ``` enum { ID_DOG = 0, ID_SPIDER, ID_WORM, ID_COUNT }; int const NumberOfEyes[ID_COUNT] = { 2, 8, 0 }; ``` Problem is that sometimes when adding/removing items, I make mistake and enum and array go out of sync. If initializer list is too long, compiler will detect it, but not other way around. So is there reliable and portable compile time check that initializer list matches the length of the array?