Re: enum safety



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.

--
Keith Thompson (The_Other_Keith) <kst-u@xxxxxxx>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: mutually referential (Pg 140 K&R2)
    ... >> Forward declared struct and union tags are incomplete, ... You can't forward declare an enum ... the values of all the members of the enumeration. ...
    (comp.lang.c)
  • Re: enum safety
    ... 'Although variables of enum types may be declared, ... you declare declare a valid ... A C enumerated type doesn't act like an enumerated type in, say, ...
    (comp.lang.c)
  • 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: Enum Names
    ... enumeration, so you can declare a data type of that enumeration, or you can ... other words if I have a value of 2 I want the corresponding "secondKey" ... Public Enum MyEnum ...
    (microsoft.public.excel.programming)
  • Re: Custom Attributes, Shared methods, Derived classes and reflection
    ... description associated with an enum value. ... enumeration value will give you the name as defined by the enumeration, ... Dim fi As FieldInfo = value.GetType.GetField ... Public Shared Function GetEnumValue ...
    (microsoft.public.dotnet.languages.vb)