enum MyType_e {A, B, C};
#define A 0
statements int
i.e. int var = A
is fully legal, although var
is not of type MyType_e
So what purpose does the enum name serve?
EDIT As per the comments below, my understanding of enums appears to be quite flawed. An enum has nothing to do with #define statements. Enums are resolved at compile time, and are typed.
Using the enum
type conveys intent.
Suppose you have a function that takes an enum
constant as an argument.
void foo(enum MyType_e e);
is self-documenting about what valid inputs are but:
void foo(int e);
is not. Moreover, the compiler may issue warnings if you attempt to pass incompatible values for the enum
type. From Annex I ("Common warnings") of the ISO C99 specification:
An implementation may generate warnings in many situations.... The following are a few of the more common situations.
[...]
- A value is given to an object of an enumeration type other than by assignment of an enumeration constant that is a member of that type, or an enumeration variable that has the same type, or the value of a function that returns the same enumeration type (6.7.2.2).
Some compilers (for example, gcc) might even generate warnings if you use switch
on an enum
type but neglect to handle all of its constants and don't have a default
case.
While you can perfectly say
int var = A
the variant
enum mytype var = A
is better for documentatory reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With