Go through Enum values in C

0

Do you have some way to go through the values of Enum in C and display in string format, like in Java, C # and other languages?     

asked by anonymous 10.12.2016 / 14:56

1 answer

1

C is a very basic language, does not have an infrastructure to make the programmer's life easier. His philosophy is to give power and flexibility, as well as transparency in the use of resources, not ease, so you have to turn around to get the result you want. A simple way is to create an 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);
    }
}

See running on ideone and on CodingGround .

In the OS there is a solution that keeps both synchronized , but honestly it's a mess.

There are other techniques, some of which can be very sophisticated. One that may help if the values of the enumeration elements are scattered is to have some auxiliary functions that tie the loop to you both by picking values and names of the elements, you would probably pass a pointer to a function that would have the loop body. Each new enumeration would have to have a set of functions with its own implementation dealing right what it needs. You would probably have to use switch to handle each element. So you're just creating an abstraction.

You can even create your own reflection system with a precompiler, but nobody does this. If it's so important, it might be the case to dare another language, but it's never that necessary.

    
10.12.2016 / 15:34