Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...