An enum is a user-defined type consisting of a fixed list of named constants. In the following example, the enumeration type is called color and contains three constants: RED, GREEN and BLUE.
enum color { RED, GREEN, BLUE };
The color type can be used to create variables that may hold one of these constant values. In C, the variable declaration must be preceded by enum, whereas this is optional in C++.
int main(void) {
enum color c = RED;
}
Enum variables may also be declared when the enum is defined, by placing the variable names before the final semicolon. This position is known as the declarator list.
enum color { RED, GREEN, BLUE } c, d;
Enum Example
The switch statement
provides a good example of when enumerations can be useful. Compared to using ordinary constants, the enumeration has the advantage that it lets the programmer clearly specify what values a variable should be allowed to contain.
switch(c) {
case RED: break;
case GREEN: break;
case BLUE: break;
}
Bear in mind that enums in C are not typesafe, unlike their C++ equivalent. It is up to the programmer to ensure that enum types and constants are used correctly, as most compilers will not enforce this. Enums in C simply provide a way to group a set of integer constants and have them be automatically numbered. For this purpose, the enum identifier is not strictly necessary and may optionally be omitted.
enum { RED, GREEN, BLUE } c;
Enum Constant Values
Enumerated constants are of the int type. Usually there is no need to know the underlying values that these constants represent, but in some cases it can be useful. By default, the first constant in the enum list has the value zero and each successive constant is one value higher.
enum color {
RED /* 0 */
GREEN /* 1 */
BLUE /* 2 */
};
These default values can be overridden by assigning values to the constants. The values can be computed and do not have to be unique.
enum color {
RED = 5, /* 5 */
SCARLET = RED, /* 5 */
BLUE = RED+2, /* 7 */
};
Enum Conversions
The compiler can implicitly convert an enumerated constant to an integer. An integer can also be converted back into an enum variable.
int i = RED;
enum color c = i;
Some compilers warn when an integer is assigned to an enum variable since this makes it possible to assign a value that is not one of its specified constants. To suppress this warning, an explicit type cast can be used.
enum color c = (enum color)i;
Enum Scope
An enum does not have to be declared globally. It can also be placed locally within a function, in which case it will only be usable within the function in which it was defined.
/* Global enum */
enum speed { SLOW, NORMAL, FAST };
int main(void) {
/* Local enum */
enum color { RED, GREEN, BLUE };
}