Wednesday, 30 January 2019

Mapping enum to string in C Language

Sometimes we require to map enum value to string. Say for example, mapping error enum value to string for storing in logs. Here I would like to explain a technique which is used in Linux kernel. It seems more efficient and easy to map. 

Step 1:

Define enum as we normally do in c-programing. For example:

    enum fruits {
        APPLE = 0,
        MANGO,
        ORANGE,
        BANANA,
        MAX_FRUITS,
    };

Step 2:

Define constant array of strings as follows. This will helps to map enum to strings.

static const char * const fruit_names[] = {
        [APPLE] = "Apple",
        [MANGO] = "Mango",
        [ORANGE] = "Orange",
        [BANANA] = "Banana"
};

Lets test it

Here is a small code to test the enum and strings that we defined:

int main(void)
{
        int i = 0;
        printf("The name of fruit is %s\n", fruit_names[APPLE]);
        printf("The name of fruit is %s\n", fruit_names[BANANA]);
        printf("The name of fruit is %s\n", fruit_names[MANGO]);
        /*  Using for loop */
        printf("\nUsing loop to retrieve strings\n\n");
        for(i =  0;  i < MAX_FRUITS; i++)
               printf("The name of fruit is %s\n", fruit_names[i]);

        return 0;
}


Lets compile and see the results:

gcc map_enum_to_string.c -o map_string

./map_string

The name of fruit is Apple
The name of fruit is Banana
The name of fruit is Mango

Using loop to retrieve strings

The name of fruit is Apple
The name of fruit is Mango
The name of fruit is Orange
The name of fruit is Banana

That's all

Its so simple to map enum to strings. And also easy to modify. May be we can use header file and a function to retrieve string in larger systems. 

References:

Code in Linux kernel:
https://github.com/torvalds/linux/blob/master/drivers/iio/industrialio-core.c

Stackoverflow and other locations:
https://stackoverflow.com/questions/147267/easy-way-to-use-variables-of-enum-types-as-string-in-c
http://www.linux-pages.com/2013/02/how-to-map-enum-to-strings-in-c/