-
Enum question
Hi all!
Is it possible somoehow to fetch the name of an enumerated var?
eg: enum {foo=1,boo=2}
Well, I would like to get 'foo' from this and not its value to find out if that name is enumerated.
Is this possible, or stupid question? -:) (Most likely the latter...-:)
Thanks
-
Hi,
Too bad, it would be useful sometimes.. Anyway, thanks, then I leave it alone.
Bye
-
Not from the enumeration, but you can make a string array to get it from:
Code:
enum {Alpha=0, Beta, Gamma};
char* Names[] = {"Alpha", "Beta", "Gamma"};
printf("%s", Names[Alpha]);
Make sure your enumeration starts at 0.
-
This is a variation of something I've used to do this.
Code:
#include <stdio.h>
#include <string.h>
enum EType
{
#define GET_ENUM
#include "test.mh"
MY_TOTAL
};
static const char *const EnumText [ MY_TOTAL ] =
{
#define GET_ENUM_TEXT
#include "test.mh"
};
static const char *const Description [ MY_TOTAL ] =
{
#define GET_DESCRIPTION
#include "test.mh"
};
int main(void)
{
enum EType i;
for ( i = 0; i < MY_TOTAL; ++i )
{
printf("(%d) %-5s \"%s\"\n", i, EnumText [ i ], Description [ i ]);
}
return 0;
}
/* my output
(0) ALPHA "This is a description of this element."
(1) BETA "The next item has no description."
(2) GAMMA ""
(3) DELTA ""
*/
The multiply-included [test.mh] is like the following.
Code:
/* Macro Definition */
#if defined(GET_ENUM)
#define MACRO(tag,desc) tag,
#elif defined(GET_ENUM_TEXT)
#define MACRO(tag,desc) #tag,
#elif defined(GET_DESCRIPTION)
#define MACRO(tag,desc) desc,
#else
#define MACRO(tag,desc)
#endif
/* Macro Binding */
MACRO(ALPHA, "This is a description of this element.")
MACRO(BETA, "The next item has no description.")
MACRO(GAMMA, "")
MACRO(DELTA, "")
/* Macro Un-Definition */
#undef MACRO
#if defined(GET_ENUM)
#undef GET_ENUM
#elif defined(GET_ENUM_TEXT)
#undef GET_ENUM_TEXT
#elif defined(GET_DESCRIPTION)
#undef GET_DESCRIPTION
#endif
There are other variations as well.
-
Hi!
Wow sounds good, I will try this. Thanks for the help for everyone!