简体   繁体   English

将枚举映射到C中的字符串的好方法

[英]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: 我有一堆枚举(如果您想知道的话,来自libvirt库):

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. 即,VAL_A的状态为“意思_A”,VAL_B的状态为“意思_B”,依此类推。 In php or perl or python, I would generate a key:val pair and return the results in O(1) time. 在php或perl或python中,我将生成一个key:val对,并以O(1)时间返回结果。 Is there an efficient way to map these to meaningful strings in C? 有没有一种有效的方法可以将这些映射到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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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