在C语言中,如何为每个枚举的文字循环,而这些文字没有连续的值 [英] In C how to loop for each enumerated literal where the literals do't have consecutive values

查看:446
本文介绍了在C语言中,如何为每个枚举的文字循环,而这些文字没有连续的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下枚举文字

Suppose i have the following enumerated literal

enum
{
valueA = 5,
valueB = 7,
valueC = 9,
valueD = 14,
valueE = 15
}myEnumType; 

,我想遍历每个文字 例如

and i want to loop through each literal eg

for (enumType myValEnum = valueA; myValEnum <= valueE; myValEnum++)
{
    MyFunction(mValEnum);
}

那行得通还是我最终会用值5,6,7,8,9,10,11,12,13,14,15调用MyFunction吗?

will that work or will I end up calling MyFunction with values 5,6,7,8,9,10,11,12,13,14,15 ?

推荐答案

您无法做到这一点,因为C中的枚举不支持"foreach"类型的迭代.基本上,枚举只是别名整数,带有很少有额外的支持.

You can't do that, there's no support for a "foreach" type of iteration over the enumeration in C. Basically, enumerations are just aliased integers, with little extra support.

您需要使用一个映射表,该表允许您将连续索引映射到枚举类型的值:

You need to use a mapping table, that allows you to map consecutive indices to values of the enumerated type:

static const myEnumType myEnumMap[] = { valueA, valueB, valueC, valueD, valueE};

然后您可以在该数组上使用普通循环:

then you can use a plain loop over that array:

for(size_t i = 0; i < sizeof myEnumMap / sizeof *myEnumMap; ++i)
{
  const myEnumType ie = myEnumMap[i];
  /* process ie */
}

请注意,myEnumMap的类型是枚举的类型,它不是简单的整数数组".

Note that the type of myEnumMap is the type of your enumeration, it's not a plain "array of integers".

这有一个缺点,要求枚举被枚举两次(在其自己的定义中一次,然后在myEnumMap初始值设定项中再次).可以使用宏技巧(例如 X宏)解决该问题,但并没有真正的方便/简便的方法.

This has the downside of requiring the enum to be enumerated twice (once in its own definition, then again in the myEnumMap initializer). It's possible to work around that using macro trickery (such as X macros), but there's no real convenient/easy way to do it.

这篇关于在C语言中,如何为每个枚举的文字循环,而这些文字没有连续的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆