Re: enum safety



Ian Collins <ian-news@xxxxxxxxxxx> writes:
Keith Thompson wrote:
[...]
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.

Exactly (except that the names of the constants follow the scoping
rules of ordinary identifiers rather than of macros, which IMHO is a
considerable advantage).

It's the lack of type
safety I don't like.

Welcome to C! 8-)}

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.

A C enumerated type is what it is. No more, no less. As long as you
keep that in mind, and *don't* confuse it with similar features in
other languages, they're not that hard to use.

You can have an enumerated type for which only the named values are
considered valid. Assigning some other value is then a logical bug in
your program, one that the compiler unfortunately won't help you
detect (unless you write your own range-checking code). But nothing
else in C will detect this kind of logical error either (unless you
write your own range-checking code). What the "enum" construct gives
you is a convenient way for the compiler to assign consecutive values
to your constants, and to choose a type that can hold all of them.

Or you can have an enumerated type where only some of the valid values
have names assigned to them, and assigning some other value is not an
error:
enum card_rank { ace = 1, jack = 11, queen = 12, king = 13 };

Or you can have an anonymous enumerated type if all you're interested
in is the constants:
enum { MAX_LENGTH = 256 };

It might have made more sense to have three different language
constructs for these three things. But if we were going to insist on
everything making sense, we probably wouldn't be using C.

--
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"
.