'C' enum syntax problem

Clayton Cramer cramer at optilink.UUCP
Thu Apr 27 03:02:01 AEST 1989


In article <643 at mitisft.Convergent.COM#, kemnitz at mitisft.Convergent.COM (Gregory Kemnitz) writes:
# # 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). 
# Another thing that won't work is
# 
#     typedef enum WEEK {
#       MONDAY, TUESDAY, WEDNESDAY,
#       THURSDAY, FRIDAY,
#       SATURDAY, SUNDAY
#     } ;
# 
#     WEEK workweek;
# 
#     switch (workweek) {
# 	 case MONDAY: ...
# 	 case TUESDAY: ...
# 
# 	 ....
# 
# Lots of compilers will barf in the switch(), unless you use this
# 
#     switch ((int) workweek) {
# 
# which sucks.  
# 
# # Is there a work around ?
# 
# The easiest and most elegant workaround (and it always seems to work) is
# 
# #define MONDAY 0
# #define TUESDAY 1
# ...
# 
# typedef short WEEK
# typedef short WEEKEND
# 
# Then switches, etc will work fine.
# 
# 				Greg Kemnitz

ANSI compilers (both of them!) know that enums are ints, and don't
require type casting to use them as ints.  There are two great advantages
to using enums rather than #defines:

1. Type checking.

2. Debugger symbols.

In particular, dbx lets you see your enum variable as _Tuesday_, not
2, which greatly simplifies debugging -- especially when you have
219 items in the enumerated type.  (Unfortunately, Microsoft CodeView,
for all its other virtues, doesn't know about enumerated types -- it
doesn't even give you a number -- just tells you it can't display
the value.  That's DUMB!)

Of course, if portability to antique non-ANSI compilers is important,
you may want to kludge in #defines.

-- 
Clayton E. Cramer                   {pyramid,pixar,tekbspa}!optilink!cramer
Governments that don't trust most people with weapons, deserve no trust.
----------------------------------------------------------------------------
Disclaimer?  You must be kidding!  No company would hold opinions like mine!



More information about the Comp.lang.c mailing list