Link to home
Start Free TrialLog in
Avatar of luonght
luonght

asked on

Writing a function for an enumerated data type

I define an enumerated data type for 4 colors as follows:

enum colors {white, blue, cyan, green};

How do I write a function that accepts a parameter of the above type. The function must print out the name of the color.

Many thanks.

Luong
ASKER CERTIFIED SOLUTION
Avatar of terrycj
terrycj

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ozo
/* here's a trick I sometimes use: */
#define table\
        x(white,=0)\
        x(blue,)\
        x(cyan,)\
        x(green,)\
        y\
/*end table*/
#define x(color,value)       color value,
#define y       num_colors
enum colors{
        table
};
#undef x
#undef y
#define x(color,value)       #color,
#define y
char *colors[]={
        table
};
main(int argc,char *argv[]){
        enum colors n;
        n = atoi(argv[1]);
        if( white <= n && n < num_colors ){ printf("%s\n",colors[n]); }
}

Avatar of terrycj
terrycj

ozo: yes, i have too, but i don't like it very much.

my main trouble with this is that it creates both the enum
definition and the colors array declaration in the same file.
for any project of a reasonable size, you'd want the colors
array to be in the file (say) print_colors.c and the enum to
be in a .h file that was included by lots of .c files.

also, i'd take out the =0 in the enum spec
and use n>0 not white <= n
in the checking since that doesn't rely on
white being first named. it does rely on the first element
in the enum having value 0 (as it will have, unless explicitly
given some other value). this is far less likely to be changed
by some unsuspecting well-intentioned later programmer.

nits, i know.

i solve things like this with make and m4 (or perl or awk etc.).
then i get to have a simple file containing only (e.g.)

color(white)
color(blue)
color(cyan)
color(green)

and i can do anything i want - including writing the checking
function, etc.

but i'm sure that's more machinery than luonght would want to
wheel in...

terry.


For a large project, I'd put the
#define table
in a .h. Each .c can then construct whatever they need from it.
I agree that I should have compared n with 0 instead of white before indexing.
And using Perl to generate a C program works well too.
ok, i'm with you on the split up (.c vs .h).

where to next?

/* you could also build something like: */
#define x(color)      if( n == color ){ puts(#color); }
void printcolor(enum color n){
#table
}

Avatar of luonght

ASKER

Adjusted points to 90