0

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the reference to X macros. I didn't know it under that name, but it's a technique I find invaluable for C programming.
-2

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.

8 Comments

"You might be better off just remembering which numbers to use for certain names in your head" - is that a joke?
No, why would you think it is? The enum doesn't add any functionality to C, just convenience. When it ceases to be convenient, you're better off not using it.
Well, you can comment them. I see nothing objectionable about it. And like I said, #define could also do the job.
Commenting magic numbers still leaves a maintenance problem (what if I want to change all the values?). #defines are better than nothing, but debuggers usually understand enums. Enums also express intent better (when used appropriately).
My project is a rather extreme example of what an incredibly horrible idea "magic numbers" are...I have an enumeration of World Health Organization racial codes...for the six we are using in our app, the values are 10025, 20289, 20545, 20768, 21063, and 21311. They each represent a different race. Also the idea of using #define has no application to my question, how would it possibly help me? ...-1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.