'C' enum syntax problem

Shankar Unni shankar at hpclscu.HP.COM
Wed Apr 26 11:00:47 AEST 1989


> >    typedef enum WEEK {
> >      MONDAY, TUESDAY, WEDNESDAY,
> >      THURSDAY, FRIDAY,
> >      SATURDAY, SUNDAY
> >    } ;
> >    typedef enum WEEK_END {
> >      SATURDAY, SUNDAY
> >    } ;
> > 
> > 	redeclaration of SATURDAY
> > 	redeclaration of SUNDAY
> > 
> > Does it mean that subsets of an enum cannot be defined ?
> > Is this a bug in my C Compiler ?
> 
> Lots of C compilers just turn enums into things that are essentially
> #defines (and barf on them when the symbol is reused). 

That is not the reason why it barfs. The reason why it complains is that
that piece of code is illegal. Period.

While enum's are not quite like #defines, the way that the enumerated
constants behave certainly makes it look that way. each occurrence of
an identifier inside an enum definition is a definition of that identifier.
Thus, in your example, SATURDAY is defined twice, once with a value of 5
and once with a value of 0.

What you are trying to do is something like the Pascal construct:

  type
      week = (monday, tuesday, ..., sunday);
      weekend = saturday .. sunday;

Where weekend is essentially a subtype of week.

So instead of trying a literal translation, try one based on the intent.
You want WEEK_END to be a subtype of WEEK? No problem:

    typedef enum WEEK WEEK;
    typedef enum WEEK WEEK_END;

And use it as

    WEEK day = MONDAY;
    WEEKEND holiday = SATURDAY;
    
What, you want range checking? HAHAHAHAH!!!!!
----
Shankar.



More information about the Comp.lang.c mailing list