Vorac
Vorac

Reputation: 9114

What purpose does the enum name serve?

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.

Upvotes: 15

Views: 2296

Answers (3)

jamesdlin
jamesdlin

Reputation: 89965

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.

Upvotes: 11

stdcall
stdcall

Reputation: 28880

The answers above are good and correct, I just want to add that certain debuggers, are able to show the enum name when hovering or mointoring an enum type variable. This really helps clarity, especially when enums are used for states in state machine implementation.

Upvotes: 1

glglgl
glglgl

Reputation: 91017

While you can perfectly say

int var = A

the variant

enum mytype var = A

is better for documentatory reasons.

Upvotes: 3

Related Questions