Browse Enum values in C

Asked

Viewed 438 times

0

Do you have any way of going through the values of Enum in C and display in format string, as in Java, C# and other languages?

1 answer

1


C is a very basic language, does not have an infrastructure to facilitate the life of the programmer. His philosophy is to give power and flexibility, in addition to transparency of the use of resources, and not ease, so he has to turn to get the result he wants. A simple way is to create a array with the names in the same positions as the enumeration and use them:

#include <stdio.h>

int main() {
    //o DirecaoLast é só para determinar o final, só funciona se usar valores padrões
    typedef enum direcao { Norte, Sul, Leste, Oeste, DirecaoLast } Direcao;
    const char* DirecaoNames[] = { "Norte", "Sul", "Leste", "Oeste" };
    for (int i = 0; i < DirecaoLast; i++) {
        Direcao direcao = i;
        printf("%s = %d\n", DirecaoNames[i], direcao);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

In the OS there is a solution that keeps both synchronized, but honestly it’s a complication for nothing.

There are other techniques, some can be very sophisticated. One that can help in case the values of the elements of the enumeration are dispersed is to have some auxiliary functions that loop for you both taking values, and names of the elements, probably pass a pointer to function that would have the loop body. Each new enumeration would have to have a set of functions with its own implementation treating right what it needs. It would probably have to use switch to treat each element. So you’re just creating an abstraction.

You can even create your own reflection system with a pre-compiler, but nobody does that. If it is so important, perhaps it is the case to dare another language, but it is never so necessary.

  • I couldn’t use here, I tried to assign a char *s[]; to an Enum of professions,

  • I showed you working, if you tried to do and failed is another problem, can open a new question posting that made us to see where it went wrong specifically in this case. The general solution, that was the request, It is given.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.