Enum to String C++

Enum to String C++

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

const char * getTextForEnum( int enumVal )
{
  return EnumStrings[enumVal];
}

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

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

Enum to String C++

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

   return myStringMap[Enum::Apple];

Leave a Reply

Your email address will not be published.