77

I commonly find I need to convert an enum to a string in c++

I always end up doing:

enum Enum{ Banana, Orange, Apple } ;

char * getTextForEnum( int enumVal )
{
  switch( enumVal )
  {
  case Enum::Banana:
    return "bananas & monkeys";
  case Enum::Orange:
    return "Round and orange";
  case Enum::Apple:
    return "APPLE" ;

  default:
    return "Not recognized..";
  }
}

Is there a better or recognized idiom for doing this?

3
  • 2
    Perhaps use std::map<int, std::string> instead of enum and switch? With a bit of wrapping into an object you could make it smart enough to be reusable as an error code lookup and handler for all your apps. Commented Jun 8, 2011 at 15:44
  • 7
    One improvement is to omit the 'default:' clause whilst turning up the warning level on your compiler and treating warnings as errors. This way, if you ever extend the list of enums, the compiler will warn and fail on your switch statement, reminding you to extend the switch as well. Some people say you should always have a default, but I believe this is a scenario where the lack of can actually help you. Commented Jun 8, 2011 at 15:46
  • As much as you don't like this technique, it has some good value to is. As @BrianO'Kennedy mentions if you omit the default, with the proper compiler setting, you will get a warning when new enum values are added and no case is found, so you can then add them. Also this won't break when someone changes the order of the enums. It is also robust enough not to access memory outside an acceptable range when people use an array of strings and index into it...or out of it!!! ...and this might get very well optimized by a compiler if performance is important. Commented Mar 19 at 5:09

3 Answers 3

52
enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };

const char * getTextForEnum( int enumVal )
{
  return EnumStrings[enumVal];
}
Sign up to request clarification or add additional context in comments.

13 Comments

Works only for continuous enums.
@SasQ, I have a more extensive answer here: stackoverflow.com/a/11586083/5987 Lots of other good suggestions in that thread too.
@GangaiJohann that's only if it's a member function. My practice is to make as few changes to the code presented in the question as possible, to avoid unnecessary distractions.
And there is a code generator for that: th-thielemann.de/tools/cpp-enum-to-string.html
@ekkis I'd use std::map<std::string,enum>.
|
23

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

Comments

14

You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.