You could play C preprocessor tricks notably with X-macros (see e.g. this).
You could have a macro invoking some macro P
on each animal
#define DO_ANIMALS(P) \
P(cat) \
P(dog) \
P(elephant)
then use it to declare the enum
enum animals_en {
#define DECLARE_ANIMAL(An) En,
DO_ANIMALS(DECLARE_ANIMAL)
};
and later use it to convert a string s
to the enum animals_en
enum animals_en convert_string_to_animal(const char*s) {
#define CHECK_STRING_ANIMAL(An) if (!strcmp(s, #An)) return An;
DO_ANIMALS(CHECK_STRING_ANIMAL)
fprintf(stderr, "bad animal %s\n", s); exit(EXIT_FAILURE);
}
You may want to look at the preprocessed form obtained with gcc -Wall -C -E yoursource.c > yoursource.i
then use some editor or pager on the generated yoursource.i
to understand more how that works.
Read documentation of GNU cpp, notably stringification & concatenation.
You could also improve this code to generate something similar to the answer from Vlad from Moscow.
Such tricks would work both in C and in C++, but are more C-like. (In C++11 you would rather try having templates).
` works in C++? – Pranit Kothari Dec 30 '14 at 09:18
. And It should be in C. – webpersistence Dec 30 '14 at 09:19
. They were from html code. – webpersistence Dec 30 '14 at 09:20