如何通过C中的相关数字访问枚举中的元素?
我在C中的枚举如下:
enum menu
{
PASTA,
PIZZA,
DIET_COKE,
MOJITO,
};
由于我没有明确提到与这些元素相对应的整数值,因此分别为它们分别分配了值0,1,2和3。
假设我决定在我的枚举中再添加100个左右的项目。 那么,是否有一种方法可以按照与之关联的数字访问这些元素? (就像我们如何使用其索引访问数组的元素)
I have an enumeration in C as follows:
enum menu
{
PASTA,
PIZZA,
DIET_COKE,
MOJITO,
};
Since I haven't explicitly mentioned the integer values corresponding to these elements, they are assigned values 0,1,2, and 3 respectively.
Say I decide to add another 100 or so items to my enum.
Then is there a way to access these elements by the number they are associated with?
(Like how we can access an element of an array using its index)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些枚举只不过是在C中命名常数
。
使用枚举,编译器会自动为您做到这一点。因此,除非您为它们创建一个数组,否则无法在C中以您想要的方式访问枚举。
更新示例
一个示例用例,以显示如何在enum的随附作为索引的附带来实现字符串列表:
这是一个输出演示:
The enums are nothing but named constants in C. Same as you declare a const using
for example.
With the enum the compiler does that for you automatically. So there is no way to access enums in a way you want in C, unless you create an array for them.
Update for an example
An example use case to show how do you implement a string list with the accompany of enum as index:
This is an output demo: