Home > Software engineering >  How do I access the an element in an enumeration by the associated number in C?
How do I access the an element in an enumeration by the associated number in C?

Time:05-22

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)

CodePudding user response:

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.

Update for an example

An example use case to show how do you implement a string list with the accompany of enum as index:

#include <stdio.h>

char *stringsOfMenu[] = {
    "Pasta",
    "Pizza",
    "Diet Coke",
    "Mojito"
};

enum menuIndex {
    PASTA,
    PIZZA,
    DIET_COKE,
    MOJITO
};

int main(void) {
    
    // For example you show menu on the screen first
    puts("Please select");
    puts("-------------");
    for(int i = 0; i <= MOJITO; i  ) {
        printf("[%d] - %s\n", i 1, stringsOfMenu[i]);
    }
    putchar('\n');
    printf("Make a choice: ");
    int choice = -1;
    scanf("%d", &choice);
    
    if(choice <= 0 || choice > MOJITO 1) {
        puts("Not a valid choice");
        return 1;
    }
    
    // Note that the choice will contain the counting number.
    // That's why we convert it to the index number.
    printf("Your choice %s is in progress, thank you for your patience!\n", stringsOfMenu[choice-1]);
    return 0;
}

This is an output demo:


Please select
-------------
[1] - Pasta
[2] - Pizza
[3] - Diet Coke
[4] - Mojito

Make a choice: 2
Your choice Pizza is in progress, thank you for your patience!

  • Related