Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting mismatched array <-> enum initializers

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?

like image 284
user694733 Avatar asked May 04 '12 10:05

user694733


1 Answers

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.

like image 91
Oliver Charlesworth Avatar answered Oct 05 '22 23:10

Oliver Charlesworth