Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What purpose does the enum name serve?

Tags:

c

enums

  • An enum is a "named collection of constants": enum MyType_e {A, B, C};
  • Those constants are declared in the parent scope of the enum i.e. if the enum is declared in file scope, and is unnamed, it is equivalent to a series of e.g.#define A 0 statements
  • The underlying type for enum constants is always 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.

like image 936
Vorac Avatar asked Apr 15 '13 06:04

Vorac


2 Answers

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.

like image 173
jamesdlin Avatar answered Sep 22 '22 18:09

jamesdlin


While you can perfectly say

int var = A

the variant

enum mytype var = A

is better for documentatory reasons.

like image 30
glglgl Avatar answered Sep 21 '22 18:09

glglgl