Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I access the an element in an enumeration by the associated number in C?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The enums are nothing but named constants in C. Same as you declare a const using

#define PASTA 0
#define PIZZA 1
#define DIET_COKE 2
#define MOJITO 3

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading