Incomputer programming, anenumerated type (also calledenumeration,enum, orfactor in theR programming language, acondition-name in theCOBOL programming language, astatus variable in theJOVIAL programming language, anordinal in thePL/I programming language, and acategorical variable in statistics) is adata type[a] consisting of a set of namedvalues calledelements,members,enumeral, orenumerators of the type. The enumerator names are usuallyidentifiers that behave asconstants in the language. An enumerated type can be seen as a degeneratetagged union ofunit type. Avariable that has beendeclared as having an enumerated type can be assigned any of the enumerators as a value. In other words, an enumerated type has values that are different from each other, and that can be compared and assigned, but are not generally[b] specified by the programmer as having any particular concrete representation in thecomputer's memory;compilers andinterpreters can represent them arbitrarily.
For example, the foursuits in a deck of playing cards may be four enumerators namedClub,Diamond,Heart, andSpade, belonging to an enumerated type namedsuit. If a variableV is declared havingsuit as its data type, one can assign any of those four values to it.
Although the enumerators are usually distinct, some languages may allow the same enumerator to be listed twice in the type's declaration. The names of enumerators need not be semantically complete or compatible in any sense. For example, an enumerated type calledcolor may be defined to consist of the enumeratorsRed,Green,Zebra,Missing, andBacon. In some languages, the declaration of an enumerated type also intentionally defines anordering of its members (High,Medium andLow priorities); in others, the enumerators are unordered (English,French,German andSpanish supported languages); in others still, an implicit ordering arises from the compiler concretely representing enumerators as integers.
Some enumerator types may bebuilt into the language. TheBoolean type for example is often a pre-defined enumeration of the valuesFalse andTrue. A unit type consisting of a single value may also be defined to representnull. Many languages allow users to define new enumerated types.
Values and variables of an enumerated type are usually implemented with someinteger type as the underlying representation. Some languages, especiallysystem programming languages, allow the user to specify the bit combination to be used for each enumerator, which can be useful to efficiently represent sets of enumerators as fixed-length bit strings. Intype theory, enumerated types are often regarded astagged unions ofunit types. Since such types are of the form, they may also be written as natural numbers.
Some early programming languages did not originally have enumerated types. If a programmer wanted a variable, for examplemyColor, 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 tomyColor. Other techniques assigned arbitrary values to strings containing the names of the enumerators.
These arbitrary values were sometimes referred to asmagic 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, make 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 (seeinformation 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. A further advantage is that enumerated types can allow compilers to enforce semantic correctness. For instance:myColor = TRIANGLE can be forbidden, whilstmyColor = REDis accepted, even ifTRIANGLE andRED are both internally represented with the value1.
Conceptually, an enumerated type is similar to a list ofnominals (numeric codes), since each possible value of the type is assigned a distinctive natural number. A given enumerated type is thus a concrete implementation of this notion. When order is meaningful and/or used for comparison, then an enumerated type becomes anordinal type.
Programming languages tend to have their own, oftentimes multiple,programming styles andnaming conventions. The variable assigned to an enumeration is usually a noun in singular form, and frequently follows either aPascalCase oruppercase convention, whilelowercase and others are seen less frequently.
WhileALGOL 60 itself has no enumeration type, several languages descended from it do. In particular, Pascal had a strong influence on the design of Ada.
InPascal, an enumerated type can be implicitly declared by listing the values in a parenthesised list:
varsuit:(clubs,diamonds,hearts,spades);
The declaration will often appear in a type synonym declaration, such that it can be used for multiple variables:
typecardsuit=(clubs,diamonds,hearts,spades);card=recordsuit:cardsuit;value:1..13;end;varhand:array[1..13]ofcard;trump:cardsuit;
The order in which the enumeration values are given matters. An enumerated type is an ordinal type, and thepred andsucc functions will give the prior or next value of the enumeration, andord 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 extendedsucc function. Some other Pascal dialects allow it via type-casts. Some modern descendants of Pascal, such asModula-3, provide a special conversion syntax using a method calledVAL; Modula-3 also treatsBOOLEAN andCHAR as special pre-defined enumerated types and usesORD andVAL for standard ASCII decoding and encoding.
Pascal style languages also allow enumeration to be used as array index:
varsuitcount:array[cardsuit]ofinteger;
InAda, the definition of enumerated types is similar to Pascal, replacing the use of "=" with "is":
typeCardsuitis(clubs,diamonds,hearts,spades);
In addition toPred,Succ,Val andPos Ada also supports simple string conversions viaImage andValue.
Similar to C-style languages Ada allows the internal representation of the enumeration to be specified:
forCardsuituse(clubs=>1,diamonds=>2,hearts=>4,spades=>8);
Ada also allows the number of bits of the enumeration to be specified in a straightforward manner, unlike C-style languages which have inconsistent support often leading to subtlemiscompilation errors.[1] For example:
forCardsuit'Sizeuse4;-- 4 bits
Additionally, one can use enumerations as indexes for arrays, like in Pascal, but there are attributes defined for enumerations
Shuffle:constantarray(Cardsuit)ofCardsuit:=(Clubs=>Cardsuit'Succ(Clubs),-- see attributes of enumerations 'First, 'Last, 'Succ, 'PredDiamonds=>Hearts,--an explicit valueHearts=>Cardsuit'Last,--first enumeration value of type Cardsuit e.g., clubsSpades=>Cardsuit'First--last enumeration value of type Cardsuit e.g., spades);
LikeModula-3 Ada treatsBoolean andCharacter as special pre-defined (in package "Standard") enumerated types. Unlike Modula-3 one can also define own character types:
typeCardsis('7','8','9','X','J','Q','K','A');
Neither the original PL/I nor ANSI ANSI X3.53–1976 has enumerations, but the IBM Enterprise PL/I[2] has ordinal types.
An ordinal variable cannot be used directly as a subscript or as aDO TO limit. However,
defineordinalfoo(green,with,envy);declareixordinalfoo,bar(first(:foo:):last(:foo:))fixedbin;doi=first(:foo:)tolast(:foo:);bar(i)=13;end;doix=first(:foo:)upthrulast(:foo:);i=binaryvalue(ix);bar(i)=bar(i)+1;end;doix=first(:foo:)repeatordinalsucc(ix)until(ix=first(:foo:))/* stop on wrap around. */;i=binaryvalue(ix);display(bar(i)||' at '||ix);end;
The originalK&R dialect of the programming languageC had no enumerated types.[3] In C, enumerations are created by explicit definitions (theenum keyword by itself does not cause allocation of storage) which use theenum keyword and are reminiscent ofstruct andunion definitions:
typedefenum{CLUBS,DIAMONDS,HEARTS,SPADES}CardSuit;typedefstruct{CardSuitsuit;shortintvalue;}Card;Cardhand[13];CardSuittrump;
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 defineClubs,Diamonds,Hearts, andSpades as constants of typeint, which will only be converted (silently) toenum 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,
enumCardSuit{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 anenum CardSuit by bitwise logic operations.
SinceC23, the underlying type of an enumeration can be specified by the programmer, with the same syntax as C++.[4] This allows programmers to make optimize enums by choosing a less expensive underlying type.
enumCardSuit:char{CLUBS=1,DIAMONDS=2,HEARTS=4,SPADES=8};
Enums in C are not scoped or qualified, because C lacksnamespacing features. Prior to the introduction of theconstexpr keyword in C23, enums were often used to declare compile-time constants without use of theC preprocessor.
Enumerated types in theC# 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 converted to an integer and back again, and an enum variable can have values that were not declared by the enum definition. For example, given
enumCardSuit{Clubs,Diamonds,Spades,Hearts}
the expressionsCardSuit.Diamonds + 1 andCardSuit.Hearts - CardSuit.Clubs are allowed directly (because it may make sense to step through the sequence of values or ask how many steps there are between two values), butCardSuit.Hearts * CardSuit.Spades is deemed to make less sense and is only allowed if the values are first converted to integers.
C# also provides the C-like feature of being able to define specific integer values for enumerations. By doing this it is possible to perform binary operations on enumerations, thus treating enumeration values as sets of flags. These flags can be tested using binary operations or with the enum type's builtin 'HasFlag' method.[5]
The enumeration definition defines names for the selected integer values and issyntactic sugar, as it is possible to assign to an enum variable other integer values that are not in the scope of the enum definition.[6][7][8]
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++, giving added compile-time checking. Also (as with structs), the C++enum keyword is combined with atypedef, so that instead of referring to the type asenum MyEnum, one can simply refer to it asMyEnum. This can be simulated in C using a typedef:typedefenum{VALUE_1,VALUE_2}MyEnum;
C++11 also provides a second kind of enumeration, called ascoped enumeration. These are type-safe: the enumerators are not implicitly converted to an integer type. Among other things, this allows I/O streaming to be defined for the enumeration type. Another feature of scoped enumerations is that the enumerators must be qualified by the enum name, so usage requires prefixing with the name of the enumeration (e.g.,Color::RED for the first enumerator in the example below), unless ausing enum declaration (introduced inC++20) has been used to bring the enumerators into the current scope. A scoped enumeration is specified by the phraseenum class (orenum struct). For example:
// C-style unscoped enumenumCardSuit{CLUBS,DIAMONDS,SPADES,HEARTS};// C++11-style scoped enumenumclassColor{RED,GREEN,BLUE};intmain(intargc,char*argv[]){Colorc=Color::RED;// Unscoped C-style enumCardSuitcard1=Clubs;// Can be unscopedCardSuitcard2=CardSuit::SPADES;// Usually declared scoped however}
Theunderlying type of an enumeration is an implementation-defined integral type that is large enough to hold all enumerated values; it does not have to be the smallest possible type. The underlying type can be specified directly, which allows "forward declarations" of enumerations:
// must fit in size and memory layout the type 'long'enumclassColor:long{RED,GREEN,BLUE};// forward declaration. If later there are values defined// that don't fit in 'char' it is an error.enumclassShapes:char;
Go uses theiota keyword to create enumerated constants.[9][10]
typeByteSizeintconst(_=iota// ignore first value by assigning to blank identifier; 0KBByteSize=1<<(10*iota)// 1 << (10 * 1) == 1 << 10 == 1024; in binary 10000000000MB// 1 << (10 * 2) == 1048576; in binary 100000000000000000000GB// 1 << (10 * 3) == 1073741824; in binary 1000000000000000000000000000000)
The J2SE version 5.0 of theJava programming language added enumerated types whose declaration syntax issimilar to that ofC:
enumCardSuit{CLUBS,DIAMONDS,SPADES,HEARTS};CardSuittrump;
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-generatedclass 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 theEnum abstract class, and thus an enum cannot extend anything else. An enum type cannot be instantiated directly.[11]
Internally, each enum value contains an integer, 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 directly, but one can defineoverloaded constructors that can then assign arbitrary values to self-defined members of the enum class. Defining getters allows then access to those self-defined members. The internal integer can be obtained from an enum value using theordinal() method, and the list of enum values of an enumeration type can be obtained in order using thevalues() method. It is generally discouraged for programmers to convert enums to integers and vice versa.[12] Enumerated types areComparable, using the internal integer; as a result, they can be sorted.
The Java standard library provides utility classes to use with enumerations. TheEnumSet class implements aSet of enum values; it is implemented as abit array, which makes it very compact and as efficient as explicit bit manipulation, but safer. TheEnumMap class implements aMap of enum values to object. It is implemented as an array, with the integer value of the enum value serving as the index.
Unlike C++, Java enums can have methods, constructors, and fields like any other class.
publicenumPlanet{// Planet, followed by mass and radiusMERCURY(3.303e+23,2.4397e6),VENUS(4.869e+24,6.0518e6),EARTH(5.976e+24,6.37814e6),MARS(6.421e+23,3.3972e6),JUPITER(1.9e+27,7.1492e7),SATURN(5.688e+26,6.0268e7),URANUS(8.686e+25,2.5559e7),NEPTUNE(1.024e+26,2.4746e7);publicstaticfinaldoubleG=6.67300E-11;privatefinaldoublemass;privatefinaldoubleradius;Planet(doublemass,doubleradius){this.mass=mass;this.radius=radius;}privatedoublemass(){returnmass;}privatedoubleradius(){returnradius;}doublesurfaceGravity(){returnG*mass/(radius*radius);}doublesurfaceWeight(doubleotherMass){returnotherMass*surfaceGravity();}publicstaticvoidmain(String[]args){doubleearthWeight=Double.parseDouble(args[0]);doublemass=earthWeight/EARTH.surfaceGravity();for(Planetp:Planet.values()){System.out.printf("Your weight on %s is %f%n",p,p.surfaceWeight(mass));}}}
Dynamically typed languages in the syntactic tradition of C (e.g.,Perl orJavaScript) do not, in general, provide enumerations. But in Perl programming the same result can be obtained with the shorthandstringslist andhashes (possiblyslices):
my@enum=qw(Clubs Diamonds Hearts Spades);my(%set1,%set2);@set1{@enum}=();# all cleared@set2{@enum}=(1)x@enum;# all set to 1$set1{Clubs}...# false$set2{Diamonds}...# true
Raku (formerly known as Perl 6) supports enumerations. There are multiple ways to declare enumerations in Raku, all creating a back-end Map.
enumCat<sphynx siamese bengal shorthair other>;# Using "quote-words"
enumCat ('sphynx','siamese','bengal','shorthair','other');# Using a list
enumCat (sphynx =>0,siamese =>1,bengal =>2,shorthair =>3,other =>4);# Using Pair constructors
enumCat (:sphynx(0), :siamese(1), :bengal(2),shorthair(3), :other(4));# Another way of using Pairs, you can also use `:0sphynx`
Enums were added in PHP version 8.1.
enumCardSuit{caseHearts;caseDiamonds;caseClubs;caseSpades;}
Enumerators may be backed by string or integer values to aid serialization:
enumCardSuit:string{caseHearts='H';caseDiamonds='D';caseClubs='C';caseSpades='S';}
The Enum's interface exposes a method that gives a collection of its enumerators and their names. String/integer-backed Enums also expose the backing value and methods to (attempt) deserialization. Users may add further methods.
Though Rust uses theenum keyword like C, it uses it to describetagged unions, of which enums can be considered a degenerate form. Rust's enums are therefore much more flexible and can contain struct and tuple variants.
enumMessage{Quit,Move{x:i32,y:i32},// structWrite(String),// single-element tupleChangeColor(i32,i32,i32),// three-element tuple}
Like C, Rust also supports specifying the values of each variant,
pubenumWeekday{Sunday=1,Monday=2,Tuesday=4,Wednesday=8,Thursday=16,Friday=32,Saturday=64,}
In C, enumerations assign related names to a set of integer values. InSwift, enumerations are much more flexible and need not provide a value for each case of the enumeration. If a value (termed araw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.
Alternatively, enumeration cases can specify associated values of any type to be stored along with each different case value, much as unions or variants do in other languages. One can define a common set of related cases as part of one enumeration, each of which has a different set of values of appropriate types associated with it.
In Swift, enumerations are a first-class type. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration's current value, and instance methods to provide functionality related to the values the enumeration represents. Enumerations can also define initializers to provide an initial case value and can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.
enumCardSuit{caseclubscasediamondscaseheartscasespades}
Unlike C andObjective-C, Swift enumeration cases are not assigned a default integer value when they are created. In the CardSuit example above, clubs, diamonds, hearts, and spades do not implicitly equal 0, 1, 2 and 3. Instead, the different enumeration cases are fully-fledged values in their own right, with an explicitly defined type of CardSuit.
Multiple cases can appear on a single line, separated by commas:
enumCardSuit{caseclubs,diamonds,hearts,spades}
When working with enumerations that store integer or string raw values, one doesn't need to explicitly assign a raw value for each case because Swift will automatically assign the values.
For instance, when integers are used for raw values, the implicit value for each case is one more than the previous case. If the first case doesn't have a value set, its value is 0. For the CardSuit example, suits can be numbered starting from 1 by writing:
enumCardSuit{caseclubs=1,diamonds,hearts,spades}
TypeScript adds an 'enum' data type to JavaScript.
enumCardSuit{Clubs,Diamonds,Hearts,Spades};varc:CardSuit=CardSuit.Diamonds;
By default, enums number members starting at 0; this can be overridden by setting the value of the first:
enumCardSuit{Clubs=1,Diamonds,Hearts,Spades};varc:CardSuit=CardSuit.Diamonds;
All the values can be set:
enumCardSuit{Clubs=1,Diamonds=2,Hearts=4,Spades=8};varc:CardSuit=CardSuit.Diamonds;
TypeScript supports mapping the numeric value to its name. For example, this finds the name of the value 2:
enumCardSuit{Clubs=1,Diamonds,Hearts,Spades};varsuitName:string=CardSuit[2];alert(suitName);
Anenum module was added to the Python standard library in version 3.4. It introduces the classEnum which can be extended for defining enumerated types.
fromenumimportEnumclassCardSuit(Enum):CLUBS:int=1DIAMONDS:int=2HEARTS:int=3SPADES:int=4
There is also afunctional API for creating enumerations with automatically generated indices (starting with one):
Cards:Enum=Enum("Cards","CLUBS DIAMONDS HEARTS SPADES")
Python enumerations do not enforce semantic correctness (a meaningless comparison to an incompatible enumeration always returnsFalse rather than raising aTypeError):
Color:Enum=Enum("Color","RED GREEN BLUE")Shape:Enum=Enum("Shape",["CIRCLE","TRIANGLE","SQUARE","HEXAGON"])defhas_vertices(shape:Enum)->bool:returnshape!=Shape.CIRCLEif__name__=="__main__":has_vertices(Color.GREEN)# outputs "True"
Dart has a support for the most basic form of enums and has a syntax similar to other languages supporting enums.
enumCardSuit{Clubs,Diamonds,Hearts,Spades}voidmain(){CardSuitcard=CardSuit.Clubs;// Dart uses the "switch" operator to match the value of an enum with the desired output.switch(card){caseCardSuit.Clubs:{print("Clubs");}break;caseCardSuit.Diamonds:{print("Diamonds");}break;caseCardSuit.Hearts:{print("Hearts");}break;caseCardSuit.Spades:{print("Spades");}break;default:{print("Unknown");}break;}}
Note that before Dart 3,[13] the switch operator did not guarantee the completeness of the cases. This means if you omit one case, the compiler will not raise an error.
InCOBOL a condition-variable is a normal variable with subordinate level-88 fields, known as condition-names. Each condition-name must have a VALUE clause. The VALUE clause for a condition clause may specify either a single value or a list of values.
Fortran 2003 introduced enumerators for interoperability with C; hence, the semantics is similar to C and, as in C, the enum values are just integers and no further type check is done. The C example from above can be written in Fortran as
enum,bind(C)enumerator::CLUBS=1,DIAMONDS=2,HEARTS=4,SPADES=8end enum
Fortran 2023 introduced a true enumeration type. Values are ordered sequentially as specified. Intrinsic functionsint andhuge support enumerations. The functionsnext andprevious are also available.
enumerationtype::days_of_weekenumerator::monday,tuesday,wednesday,thursday,fridayenumerator::saturday,sundayendenumerationtypetype(days_of_week)::dow:if(dow==wednesday)then print*,'hump day'end if:select case(dow)case(monday:friday)print*,'weekday'case(saturday,sunday)print*,'weekend'end select
| Visual Basic (classic) andVBA | VB.NET | VBScript |
|---|---|---|
EnumCardSuit' Zero-basedClubsDiamondsHeartsSpadesEndEnumSubEnumExample()DimsuitAsCardSuitsuit=DiamondsMsgBoxsuitEndSub Enumerated datatypes are automatically assigned the " | EnumCardSuitClubsDiamondsHeartsSpadesEndEnumSubEnumExample()DimsuitAsCardSuitsuit=CardSuit.DiamondsMessageBox.show(suit)EndSub | Not available |
Common Lisp uses the member type specifier, e.g.,
(deftypecardsuit()'(memberclubdiamondheartspade))
that 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 aCommon Lisp Object System (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, to define methods to cover an enumerated type, a method must be defined for each specific element of that type.
Additionally,
(deftypefinite-element-set-type(&restelements)`(member,@elements))
may be used to define arbitrary enumerated types at runtime. For instance
(finite-element-set-typeclubdiamondheartspade)
would refer to a type equivalent to the prior definition of cardsuit, as of course would simply have been using
(memberclubdiamondheartspade)
but may be less confusing with the function#'member for stylistic reasons.
Infunctional programming languages in theML lineage (e.g.,Standard ML (SML),OCaml, andHaskell), analgebraic data type with onlynullary constructors can be used to implement an enumerated type. For example (in the syntax of SML signatures):
datatypecardsuit=Clubs|Diamonds|Hearts|Spadestypecard={suit:cardsuit;value:int}valhand:cardlistvaltrump: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 theEnumtype class which a type can derive or implement to get a mapping between the type andInt.
Somedatabases support enumerated types directly.MySQL provides an enumerated typeENUM 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.[14]
Example:
CREATETABLEshirts(nameVARCHAR(40),sizeENUM('x-small','small','medium','large','x-large'));
Can be defined in JSON schema using the "enum" keyword.[15]
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"cardsuit":{"type":"string","enum":["Clubs","Diamonds","Hearts","Spades"]}},"required":["cardsuit"]}
XML Schema supports enumerated types through the enumeration facet used for constraining most primitive datatypes such as strings.
<xs:elementname="cardsuit"><xs:simpleType><xs:restrictionbase="xs:string"><xs:enumerationvalue="Clubs"/><xs:enumerationvalue="Diamonds"/><xs:enumerationvalue="Hearts"/><xs:enumerationvalue="Spades"/></xs:restriction></xs:simpleType></xs:element>
In Java, enumerated types are a full fledged class which means they are typesafe and can be extended by adding methods, fields or even implementing interfaces. Whereas in C#, an enumerated type is simply syntactic sugar around an integral type (typically an int) meaning they cannot be extended and are not typesafe.
{{cite web}}: CS1 maint: bot: original URL status unknown (link)Enumerationen sind die heimlichen Sieger von Java 1.5. Nach vielen Beteuerungen durch Sun, Enums seien in Java überflüssig und können einfach nachgebildet werden, wurden sie nun doch eingeführt. Die einfachste Möglichkeit einer Enumeration der Jahreszeiten sieht wie folgt aus … Das Schlüsselwort enum steht für eine spezielle Art von Klasse, die eine Enumeration definiert. …Im Gegensatz zu anderen Programmiersprachen wie C/C++ und C# kann man ihnen per Gleichheitszeichen keine ganzen Zahlen zuordnen.
{{cite web}}: CS1 maint: multiple names: authors list (link)Alt URLArchived 2013-05-27 at theWayback Machine// Poorly designed enum don't do this … Obviously (like with everything else), we can misuse this piece of sugar ending up with a system suffering from hyperglycemia. … Seeing as the underlying type of our enum is an int (can also use other integral types) it can lead to some interesting issues when using an enum as bit flags via bitwise operators.
{{cite web}}: CS1 maint: bot: original URL status unknown (link)Go's iota identifier is used in const declarations to simplify definitions of incrementing numbers. Because it can be used in expressions, it provides a generality beyond that of simple enumerations