[comp.lang.c] enum style

bill@gothamcity.jsc.nasa.gov (Bill Shirley) (05/28/91)

I started using a certain stype in enumerated type definitions 
and would like to know other C peoples' opinions about it.
I'm mostly concerned with readability/maintainability/portability.

If I have made assumptions that may not be true across all platforms
*please* tell me!

here goes...

typedef enum {	NoState,
	STATE_A, STATE_B, STATE_C, /* ... */
		NUM_STATES } State;


As a side note, I have found this to be extremely useful in debugging
where I used to have many, many #define statements for many different things!


I am correct in assuming that NUM_STATES will be the correct value always,
aren't I?

using it in cases such as:

char	*name_of_state[NUM_STATES];

(the 'zero' element normally is not used)


Anyway, I'd like to hear others' opinions (pro or con).

     ____     ____       ____			Bill Shirley
    / ___|   / ___|     / ___|			bill@gothamcity.jsc.nasa.gov
   |_|      |_|ciences |_|			_______________________________
    _omputer     _      _			Opinions expressed are obtained|
   | |___    ___| |    | |___orporation		by a room full of immortal apes|
    \____|  |____/      \____|			with unbreakable typewriters.  |
  						~~~~~~~~~~~DISCLAIMER~~~~~~~~~~~

gaynor@paul.rutgers.edu (Silver) (05/28/91)

bill@gothamcity.jsc.nasa.gov (Bill Shirley) writes:
> [Opinions on the overall style of the following enum example?  
> I'm mostly concerned with readability/maintainability/portability.]
>
> typedef enum {  NoState,
>         STATE_A, STATE_B, STATE_C, /* ... */
>                 NUM_STATES } State;

There are some drain-bamaged compilers out there that don't by default map the
first element to 0.  I recommend explicitly mapping the first element to the
desired integer, and, to avoid name clashes, prefix each of the elements with
the name of the type.  Mine tend to look like this:

    typedef enum {thing_min = 0,
                  thing_0 = thing_min,
                  thing_1,
                  thing_2,
                  ...,
                  thing_N,
                  thing_max = thing_N,
                  thing_lim}
            thing;

> NUM_STATES will be the correct value always?
Should be, unless you veer from the default ordering.  In your example, it
should have the value 4; in mine, N+1.

Regards, [Ag]