Saturday, September 5, 2009

Enumeration

An enumeration is a datatype with all the valid values defined by the programmer. In C++ an enumeration is declared.

enum TypeName { List_of_values };

that defines a new data type named TypeName whose values are the identifiers in the List of values. Each identifier is associated with an integer constant, i.e. the C++ compiler automatically preforms a identifier-to-integer mapping associating the integer 0 with the first identifier the integer 1 with the second etc.

C++ also allows the programmer to specify explicitly the values given to the identifiers:

enum NumberBase { BINARY = 2, OCTAL = 8, DECIMAL = 10, HEX = 16, HEXADECIMAL = 16 };

The integer associated with an identifier is, by default, one more than the integer associated with the preceding identifier. The integers can be declared:

enum Color { RED = 1, BLUE, GREEN, YELLOW, VIOLET };

Two ro more identifiers can have the same integer value associated with them. The enumerators (the identifiers in the enumeration) can be used wherever int or char values can be used. The enumerator is interpreted as the integer it is associated with. Enumeration and integer data can operate together as they were of the same type.

An integer value cannot be used instead of an enumerator in assignments or as a function parameter without explicit type conversion:

enum Season { SUMMER, FALL, WINTER, SPRING };
void print( Season quarter );

int figure = SUMMER; // figure <--- 0
// equivalent <--- SUMMER
Season equivalent = static_cast (figure);
// print( SUMMER )
print( static_cast (figure) );

Reference: ucalgary, anyexample, codeproject

Previous post

Next post


No comments:

Post a Comment