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?
What about a compile time assertion like the following? (Yes, there are more elaborate CT_ASSERT macros; this is to illustrate the idea.)
Now when the
NumberOfEyesarray has more or less elements thanID_COUNT, this will cause an error alongx.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.