0

I am new with C, and I found enum really nice. My programs gets a strings, and uses the enum to do cases, and then (sometimes) I need to send back a string that matches one in a enum table. Is there a way to do it with enums or should I use lookuptables? Something like this

typedef enum    {
    string1,
    string2,
    string3,
    string4,
    BADKEY                
} strings;

function(string1); //will send the integer, 
                   //but would love to be able to send the string.

function(char *string) {
...
}
Community
  • 1
  • 1
Juan
  • 521
  • 1
  • 11
  • 28
  • Thanks for the link, there are some good idea there. @QuentinUK Could you elaborate on your answer? – Juan Mar 13 '13 at 10:24
  • Also considering it is really similar (if not the same) to the previous question should I delete it? – Juan Mar 13 '13 at 10:33

2 Answers2

4

No, there's no way to get this automatically. You must implement a way, look-up tables is one solution.

The names of enum values are not "strings", they're just symbols like function and variable names; they play no role in the code generation. Once the code runs, it's all machine code with no names left.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

Just for the record, You could make use of the preprocessor's "stringify" operator.

#define MAKE_STR(enumMember) #enumMember

What this does is that it replaces enumMember with "enumMember" so you could use it as you would a string.

example:

printf("The value of %s is %d", MAKE_STR(string1), string1);

EDIT Note though that what stringify does is just surrounds whatever it's passed with quotes, so it literally stringifies whatever is written after the #.

Mohamed Tarek
  • 385
  • 3
  • 11