简体   繁体   中英

good way to map enums to strings in C

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.

Try using it as an array index:

char *strs[] = {"meaning_A", "meaning_B", "etc."};
strs[(int)enumvar - 1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM