tags:

views:

33

answers:

3

i am working on a project where i am using SysRc values as return values from some function like SUCCESS and FAILURE ond sum enums . Now i want to know how to get them print?

A: 

There is no way of doing this directly in C or C++ - you have to write functions that take enumeration values as parameters and convert them to strings.

enum E  { foo, bar };

const char * ToStr( E e ) {
    if ( e == foo ) {
           return "foo";
    }
    else {
         return "bar";
     }
}
anon
ok thanks, i just thought if there is any way to do it.
Kumar Alok
a switch would be better and less redundant, especially in gcc, where you get a nice warning on unhandled case values.
phresnel
+1  A: 

Building on top of Neil's post:

A switch statement is usually the way to go with enum values in C++. You could save some writing work by using #define-macros, but I personally avoid them.

enum E  { foo, bar };
const char * ToStr( E e ) {
    switch(e) {
    case foo: return "foo";
    case bar: return "bar";
    };
    throw std::runtime_error("unhandled enum-value"); // xxx
}

gcc will warn you about unhandled case values.

phresnel
A: 

As others have said, you can't get enum names out. However you can use X-macros to generate both the enum and the string array:

In colours.h:

#define COLOUR_VALUES \
    X(RED) \
    X(BLUE) \
    X(YELLOW)

#define X(a) a,
typedef enum {
   COLOUR_VALUES
} colour_t;
#undef X

extern char *colour_names[];

In colours.c:

#include "colours.h"

#define X(a) #a,
char *colour_names[] = {
    COLOUR_VALUES
};
#undef X

void print_colour(colour_t colour)
{
     printf("%s\n", colour_names[colour]);
}
Vicky