简体   繁体   中英

Get array, value at index from typedef enum in C

If have an enumeration like so:

typedef enum {
    ValueOne = /* some arbitrary number, NOT necessarily 0 */,
    ValueTwo = /* another number, NOT necessarily consecutive */
} MyEnumeration;

I was wondering if there is any way to get an array out of it and access a value at a specific index without doing this:

int array[2] = {ValueOne, ValueTwo};
MyEnumeration value = array[provided_index];

My problem is that in my project, the enumerations have 10-15 values, and I'd rather not create an array out of each one of them.

[Edit]: I can see how this would not be possible since typedef and enum aren't tied together at all, but I figured it wouldn't hurt to ask in case I was missing something.

No.

You will have to write the code for both the enum and the array, or use some technique to auto-generate code to reduce the maintenance burden.

This article may of be some interest to you: The New C: X Macros .

I would completely do away with the enumeration. If you have to store it in both an array and as an enumeration, there is really no point to it at all. Enumerations are macros, they don't really store any information, they just create names for numbers, which I believe are substituted in at compile time. You might be better off just remembering which numbers to use for certain names in your head or using #define.

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