Enumerated type

Enumerated type

In computer programming, an enumerated type is a data type (usually user-defined) consisting of a set of named constants called "enumerators". The act of creating an enumerated type defines an enumeration. When an identifier such as a variable is declared having an enumerated type, the variable can be assigned any of the enumerators as a value. If the programming language allows an enumerated type to be given a name, the name usually is chosen to collectively describe the enumerators in the set.

For example, the four suits in a deck of playing cards (clubs, diamonds, hearts, spades) may be four enumerators belonging to an enumerated type named "suits". If a variable is declared having "suits" as its data type, the variable can be assigned clubs, diamonds, hearts, or spades as a value.

An enumerated type need not have a complete list of enumerators, nor do the enumerators need to be ordered. However, an enumerator is usually not repeated. Furthermore, only the enumerators that are relevant may appear in the set. For example, an enumerated type called "favoriteColors" could only have three enumerators: red, green, and blue.

Note: In some languages, the boolean type is a pre-defined enumerated type with two enumerators (true and false). Also, enumerators sometimes appear in upper case letters to indicate they are constants.

Rationale

Some early programming languages did not originally have enumerated types. If a programmer wanted a variable, for example "myColor", to have a value of red, the variable red would be declared and assigned some arbitrary value, usually an integer constant. The variable red would then be assigned to "myColor". Other techniques assigned arbitrary values to strings containing the names of the enumerators.

These arbitrary values were sometimes referred as magic numbers since there often was no explanation as to how the numbers were obtained or whether their actual values were significant. These magic numbers could make the source code harder for others to understand and maintain.

Enumerated types, on the other hand, made the code more self-documenting. Depending on the language, the compiler could automatically assign default values to the enumerators thereby hiding unnecessary detail from the programmer. These values may not even be visible to the programmer (see information hiding). Enumerated types can also prevent a programmer from writing illogical code such as performing mathematical operations on the values of the enumerators. If the value of a variable that was assigned an enumerator were to be printed, some programming languages could also print the name of the enumerator rather than its underlying numerical value.

Pascal and syntactically similar languages

In Pascal, an enumerated type can be implicitly declared by listing the values in a parenthesised list: var suit: (clubs, diamonds, hearts, spades); The declaration will often appear in a type synonym declaration, such that it can be used for multiple variables:

type cardsuit = (clubs, diamonds, hearts, spades); card = record suit: cardsuit; value: 1 .. 13; end; var hand: array [ 1 .. 13 ] of card; trump: cardsuit; The order in which the enumeration values are given matters. An enumerated type is an ordinal type, and the pred and succ functions will give the prior or next value of the enumeration, and ord can convert enumeration values to their integer representation. Standard Pascal does not offer a conversion from arithmetic types to enumerations, however. Extended Pascal offers this functionality via an extended succ function. Some other Pascal dialects allow it via type-casts. Some modern descendants of Pascal, such as Modula-3, provide a special conversion syntax using a method called VAL; Modula-3 also treats BOOLEAN and CHAR as special pre-defined enumerated types and uses ORD and VAL for standard ASCII decoding and encoding.

Pascal style languages also allow for enumeration to be used as array index

var suitcount: array [cardsuit] of integer;

Ada

In Ada the use of "=" was replaced with "is" leaving the definition quite similar:

type Cardsuit is (clubs, diamonds, hearts, spades);

In addition to Pred, Succ, Val and Pos Ada also supports simple string conversions via Image and Value.

Similar to C-style languages Ada allows the internal representation of the enumeration to be specified:

for Cardsuit use (clubs => 1, diamonds => 2, hearts => 4, spades => 8);

Unlike C-style languages Ada also allows the size of the enumeration to be specified:

for Cardsuit'Size use 8;

Like Modula-3 Ada treats Boolean and Character as special pre-defined (in package "Standard") enumerated types. Unlike Modula-3 one can also define own character types:

type Cards is ("7", "8", "9", "J", "Q", "K", "A");

C and syntactically similar languages

The original K&R dialect of the C programming language did not have enumerated types, but they were added in the ANSI standard for C, which became C89. In C, enumerations are created by explicit definitions, which use the enum keyword and are reminiscent of struct and union definitions:enum cardsuit { CLUBS, DIAMONDS, HEARTS, SPADES};

struct card { enum cardsuit suit; short int value;} hand [13] ;enum cardsuit trump;C exposes the integer representation of enumeration values directly to the programmer. Integers and enum values can be mixed freely, and all arithmetic operations on enum values are permitted. It is even possible for an enum variable to hold an integer that does not represent any of the enumeration values. In fact, according to the language definition, the above code will define CLUBS, DIAMONDS, HEARTS, and SPADES as constants of type int, which will only be converted (silently) to enum cardsuit if they are stored in a variable of that type.

C also allows the programmer to choose the values of the enumeration constants explicitly, even without type. For example, enum { CLUBS = 1, DIAMONDS = 2, HEARTS = 4, SPADES = 8 }; could be used to define a type that allows mathematical sets of suits to be represented as an enum cardsuit by bitwise logic operations.

Typeless languages in the syntactic tradition of C (e.g. perl or JavaScript) do not in general provide enumerations.

C++

C++ has enumeration types that are directly inherited from C's and work mostly like these, except that an enumeration is a real type in C++, so the "enum" keyword is only used when declaring the enumeration, but the name of the enumeration properly refers to the type thereafter.

C++0x will improve enum functionally by introducing "enum classes", which limits the scope of enumeration items to the enumation type only.

Java

The J2SE version 5.0 of the Java programming language added enumerated types whose declaration syntax issimilar to that of C's: enum Cardsuit { Clubs, Diamonds, Spades, Hearts } ... Cardsuit trump ; The Java type system, however, treats enumerations as a type separate from integers, and intermixing of enum and integer values is not allowed. In fact, an enum type in Java is actually a special compiler-generated class rather than an arithmetic type, and enum values behave as global pre-generated instances of that class. Enum types can have instance methods and a constructor (the arguments of which can be specified separately for each enum value). All enum types implicitly extend the Javadoc:SE|java/lang|Enum abstract class. An enum type cannot be instantiated directly.

Internally, each enum value contains an integer, usually corresponding to the order in which they are declared in the source code, starting from 0. The programmer cannot set a custom integer for an enum value. This internal integer can be obtained from an enum value using the Javadoc:SE|name=ordinal()|java/lang|Enum|ordinal() method, and you can get the list of enum values of an enumeration type in order using the values() method. It is generally discouraged for programmers to convert enums to integers and vice versa. Enumerated types are Comparable, using the internal integer; as a result, they can be sorted.

The Java standard library provides some utility data structures to use with enumerations. The Javadoc:SE|java/util|EnumSet class implements a Set of enum values; it is implemented as a bit array, so is very compact and efficient, but is safer to use than explicit bit field manipulations. The Javadoc:SE|java/util|EnumMap class implements a Map of enum values to other things; it is implemented as an array, with the integer value of the enum value serving as the index, so is very fast.

C#

Enumerated types in the C# programming language preserve most of the "small integer" semantics of C's enums. Some arithmetic operations are not defined for enums, but an enum value can be explicitly convertedto an integer and back again, and an enum variable can have values that were not declared by the enum definition. For example, given

enum Cardsuit { Clubs, Diamonds, Spades, Hearts };

the expressions Diamonds + 1 and Hearts - Clubs are allowed directly (because it makes sense to step through the sequence of values or ask how many steps there are between two values), but Hearts * Spades is deemed to make less sense and is only allowed if the values are first converted to integers.

Visual Basic/VBA

Enumerated datatypes in Visual Basic and VBA are automatically assigned the "Long Integer" datatype and also become a datatype themselves:Enum CardSuit Clubs Diamonds Hearts SpadesEnd Enum

Sub EnumExample() Dim suit As CardSuit suit = Diamonds MsgBox suitEnd Sub

Algebraic data type in functional programming

In functional programming languages in the ML lineage (e.g., SML, OCaml and Haskell), an algebraic data type with only nullary constructors can be used to implement an enumerated type. For example (in the syntax of SML signatures):

datatype cardsuit = Clubs | Diamonds | Hearts | Spades type card = { suit: cardsuit; value: int } val hand : card list val trump : cardsuit

In these languages the small-integer representation is completely hidden from the programmer, if indeed such a representation is employed by the implementation. However, Haskell has the Enum type class which a type can derive or implement to get a mapping between the type and Int.

Lisp

Common Lisp uses the member type specifier, e.g.(deftype cardsuit () '(member club diamond heart spade))which states that object is of type cardsuit if it is #'eql to club, diamond, heart or spade. The member type specifier is not valid as a CLOS parameter specializer,however. Instead, (eql atom), which is the equivalent to (member atom) may be used (that is, only one member of the set may be specified with an eql type specifier, however, it may be used as a CLOS parameter specializer.) In other words, in order to define methods to cover an enumerated type, a method must defined for each specific element of that type.

Additionally,(deftype finite-element-set-type (&rest elements) `(member ,@elements))may be used to define arbitrary enumerated types at runtime. For instance(finite-element-set-type club diamond heart spade)would refer to a type equivalent to the prior definition of cardsuit, as of course would simply have been using(member club diamond heart spade)but may be less confusing with the function #'member for stylistic reasons.

Databases

Some databases support enumerated types directly. MySQL provides an enumerated type ENUM with allowable values specified as strings when a table is created. The values are stored as numeric indices with the empty string stored as 0, the first string value stored as 1, the second string value stored as 2, etc. Values can be stored and retrieved as numeric indexes or string values.

External links

* [http://dev.mysql.com/doc/refman/5.1/en/enum.html Enumerated types in MySQL]
* [http://www.cppreference.com/keywords/enum.html Enumerated types in C/C++]


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Look at other dictionaries:

  • Enumerated Data Type —   [engl.], Aufzählungstyp …   Universal-Lexikon

  • Data type — For other uses, see Data type (disambiguation). In computer programming, a data type is a classification identifying one of various types of data, such as floating point, integer, or Boolean, that determines the possible values for that type; the …   Wikipedia

  • Algebraic data type — In computer programming, particularly functional programming and type theory, an algebraic data type (sometimes also called a variant type[1]) is a datatype each of whose values is data from other datatypes wrapped in one of the constructors of… …   Wikipedia

  • Array data type — Not to be confused with Array data structure. In computer science, an array type is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices that can be computed at run time by the …   Wikipedia

  • Composite data type — In computer science, a composite data type is any data type which can be constructed in a program using its programming language s primitive data types and other composite types. The act of constructing a composite type is known as composition.… …   Wikipedia

  • Option type — For families of option contracts in finance, see Option style. In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional …   Wikipedia

  • Opaque data type — In computer science, an opaque data type is a user defined data type used like built in data type. It is incompletely defined in an interface, so that ordinary client programs can only manipulate data of that type by calling procedures that have… …   Wikipedia

  • Complex data type — Some programming languages provide a complex data type for complex number storage and arithmetic as a built in (primitive) data type. In some programming environments the term complex data type (in contrast to primitive data types) is a synonym… …   Wikipedia

  • Decimal data type — Some programming languages provide a built in (primitive) or library decimal data type to represent non repeating decimal fractions like 0.3 and 1.17 without rounding, and to do arithmetic on them. Examples are the decimal.Decimal type of Python …   Wikipedia

  • Document Type Definition — (DTD) is a set of markup declarations that define a document type for SGML family markup languages (SGML, XML, HTML). DTDs were a precursor to XML schema and have a similar function, although different capabilities. DTDs use a terse formal syntax …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”