This declaration:
enum fruit {
apple,
orange
};
declares three things: a type called enum fruit
, and two enumerators called apple
and orange
.
enum fruit
is actually a distinct type. It's compatible with some implementation-defined integer type; for example, enum fruit
might be compatible with int
, with char
, or even with unsigned long long
if the implementation chooses, as long as the chosen type can represent all the values.
The enumerators, on the other hand, are constants of type int
. In fact, there's a common trick of using a bare enum
declaration to declare int
constants without using the preprocessor:
enum { MAX = 1000 };
Yes, that means that the constant apple
, even though it was declared as part of the definition of enum fruit
, isn't actually of type enum fruit
. The reasons for this are historical. And yes, it would probably have made more sense for the enumerators to be constants of the type.
In practice, this inconsistency rarely matters much. In most contexts, discrete types (i.e., integer and enumeration types) are largely interchangeable, and the implicit conversions usually do the right thing.
enum fruit { apple, orange };
enum fruit obj; /* obj is of type enum fruit */
obj = orange; /* orange is of type int; it's
implicitly converted to enum fruit */
if (obj == orange) { /* operands are converted to a common type */
/* ... */
}
But the result is that, as you've seen, the compiler isn't likely to warn you if you use a constant associated with one enumerated type when you mean to use a different one.
One way to get strong type-checking is to wrap your data in a struct:
enum fruit { /* ... */ };
enum color { /* ... */ };
struct fruit { enum fruit f; };
struct color { enum color c; };
struct fruit
and struct color
are distinct and incompatible types with no implicit (or explicit) conversion between them. The drawback is that you have to refer to the .f
or .c
member explicitly. (Most C programmers just count on their ability to get things right in the first place -- with mixed results.)
(typedef
doesn't give you strong type checking; despite the name, it creates an alias for an existing type, not a new type.)
(The rules in C++ are a little different.)