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?
This is possibly a situation where X macros could be applied.
animals.x
X(DOG, 2)
X(SPIDER, 8)
X(WORM, 0)
foo.c
enum {
#define X(a,b) ID_##a,
#include "animals.x"
#undef X
};
int const numberOfEyes[] = {
#define X(a,b) b,
#include "animals.x"
#undef X
};
This not only guarantees that the lengths match, but also that the orders are always kept in sync.
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