0

I have a bunch of enums (from libvirt library if you are wondering) that look like this:

enum whatever {
    VAL_A = 1
    VAL_B = 2
    ...
}

How do I convert these to meaningful strings? That is, VAL_A has a state meaning "meaning_A", VAL_B has a state meaning "meaning_B" and so on. In php or perl or python, I would generate a key:val pair and return the results in O(1) time. Is there an efficient way to map these to meaningful strings in C? I was thinking of a switch statement, but was wondering about better approaches.

Thanks,

Vik.

waka-waka-waka
  • 1,025
  • 3
  • 14
  • 30
  • 1
    See X-Macros and SO questions such as [Counting preprocessor macros](http://stackoverflow.com/questions/8662395/counting-preprocessor-macros), [Is it possible to modify this X-macro to build a struct which includes arrays](http://stackoverflow.com/questions/13561509/is-it-possible-to-modify-this-x-macro-to-build-a-struct-which-includes-arrays) and [Displaying `#define` values in C](http://stackoverflow.com/questions/10915520/displaying-define-values-in-c) for related questions — I suspect there are others, but I've not rediscovered them yet. – Jonathan Leffler Mar 04 '14 at 17:33
  • C is as good as python -- at least if you can find a good library that performs key:val conversion. Then the matter is if you want to do dirty hacks / macros such as #include "foo.bar" twice to make it look that you only need to enter the values once as in `DIRTY_MACRO( 1,2,700,701,900);` which would produce both the key:val pairs and the enums at once. – Aki Suihkonen Mar 04 '14 at 18:29

1 Answers1

1

Try using it as an array index:

char *strs[] = {"meaning_A", "meaning_B", "etc."};
strs[(int)enumvar - 1];
Linuxios
  • 34,849
  • 13
  • 91
  • 116
  • What if my enum val has five values spaced out from 1 to 9000? in that case wouldn't I be allocating unnecessary space? – waka-waka-waka Mar 04 '14 at 17:29
  • 1
    @VikhyathReddy: Sorry, misread your comment. Then a switch is probably easier. – Linuxios Mar 04 '14 at 17:31
  • If you truly have a sparse data set, you'll either have to waste space or use something slower than O(1), such as a binary tree. I rather doubt that perl, python, etc, are actually O(1). – user3303729 Mar 04 '14 at 19:49