Re: enum safety



Keith Thompson wrote:
Ian Collins <ian-news@xxxxxxxxxxx> writes:
Army1987 wrote:
Ian Collins wrote:
Sard wrote:
Page 39 K&R2 says

'Although variables of enum types may be declared, compilers need not
check that what you store in such a variable is a valid value for the
enumeration'

This is why (in my opinion) enums are horribly broken in C.
Not necessarily. For example, you can have an object which can contain
a number up to 10 as numbers, and 11, 12 and 13 with special meanings. E.g.
enum rank { ACE = 1, JACK = 11, QUEEN = 12, KING = 13 };
enum rank foo = 7;
That illustrates the problem perfectly, you declare declare a valid
range of values for rank and then legally assign some other arbitrary
value to it. Useless.

It seems perfectly useful to me. An object of type enum range can
sensibly hold any value from 1 to 13. The values 1, 11, 12, and 13
happen to have names associated with them; the others are merely
numbers. The language guarantees that this will work (in fact, it
guarantees that values in the range 0..127 are valid).

A C enumerated type doesn't act like an enumerated type in, say,
Pascal or Ada, but it's not supposed to. It merely provides a set of
names for specific values, and an integral type that can hold all
those values.

Or in C++, where they are first class types. A C enum is little
different from a typedef and a set of #defines. It's the lack of type
safety I don't like. Maybe it as was a bad experience with come code
that tried to use enems as types, but ended up abusing them (assigning
wrong values) that made me feel this way.

--
Ian Collins.
.



Relevant Pages

  • Re: What scope is best for defining Enum type?
    ... I usually only declare Enums inside of classes when they ... Defining an enum type inside a class ... > public Class Product ... > 'Use the enumerated type within the class like this: ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Enumerated types
    ... Enum ACGroup ... I cannot then access the members of the group. ... One alternative I could try, in the mean time, is to declare a string array ...
    (microsoft.public.access.formscoding)
  • Re: enum safety
    ... 'Although variables of enum types may be declared, ... check that what you store in such a variable is a valid value for the ... you declare declare a valid ...
    (comp.lang.c)
  • Re: non-static method gotcha
    ... the declared enum, 'SubmissionSite' in your example. ... Its effect is to declare that C is not an inner class. ... extends the immediately enclosing enum type. ... decompiled anonymous class. ...
    (comp.lang.java.help)
  • Re: enum safety
    ... 'Although variables of enum types may be declared, ... you declare declare a valid ...
    (comp.lang.c)