Conceptintro
Enumeration
Also called enum, enumerated type, enumeration type, enum type, enum class, enumerator.
An enumeration is a type with a fixed set of named values, such as the colors of a traffic light. Some languages store the values as integers, and others as objects.
- Applies to
- core-languages
Idea
Some values come from a short, fixed list. A traffic light is red, amber or green. A suit is clubs, diamonds, hearts or spades. An enumeration is a type whose values are exactly the items of such a list. Wikipedia defines it as "a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type".1
from enum import Enum
class Light(Enum):
RED = 0
AMBER = 1
GREEN = 2
def after(light: Light) -> Light:
match light:
case Light.RED:
return Light.GREEN
case Light.GREEN:
return Light.AMBER
case Light.AMBER:
return Light.RED
for light in Light:
print(light.name, light.value, "then", after(light).name)
RED 0 then GREEN
AMBER 1 then RED
GREEN 2 then AMBER
An enumeration is better than a plain string or a plain number. The names show the meaning, and the type stops a program from using a value that is not in the list. Wikipedia notes that "An enumerated type can be seen as a degenerate tagged union of unit type".1 That is, it is a sum type whose variants carry no data (see Sum types).
How it works
Declaration. A program lists the names once, as in enum Light { RED, AMBER, GREEN }. Each name becomes a constant of the new type.
Integers or objects. Languages store enumeration values in two ways:
- As integers. In C, "An identifier declared as an enumeration constant has type int", and each enumerated type "shall be compatible with char, a signed integer type, or an unsigned integer type".2 In C#, an enum "is a value type defined by a set of named constants of the underlying integral numeric type".3 C++ and TypeScript numeric enums also work this way. Go has no enum keyword: a program declares typed constants, and
iota"represents successive untyped integer constants".4 - As objects. In Java, "The enum declaration defines a class (called an enum type)", and its body "can include methods and other fields".5 The JLS says that an enum class "has no instances other than those defined by its enum constants".6 Python and Kotlin enumerations are classes too.78
Iteration. Many languages can list all the values of an enumeration in declaration order. In Java, the compiler adds "a static values method that returns an array containing all of the values of the enum in the order they are declared".5 A Python enumeration "can be iterated over to return its canonical (i.e. non-alias) members in definition order".7 Kotlin has an entries property. C, C++ and Go have no built-in way to list the values.
Case analysis. A switch or a match on an enumeration can have one branch for each value. Many compilers check that every value has a branch. For Kotlin: "When you use all enum constants in a when expression, you don't need an else branch."8 C and C++ compilers can warn about a missing case.
Names and numbers. Programs often convert an enumeration value to its name, to its number, and back. These conversions are where the two models differ most: an integer enum can hold a number that has no name, and an object enum cannot.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Idiom | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | An enum class has one object for each constant, and its entries property lists them; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Idiom | A CHECK constraint or a lookup table limits a column to a fixed set of values, and some systems have an ENUM type. |
| Bash | Idiom | Bash has no enumeration type, but a set of readonly variables can name the values. |
| PowerShell | Native | The enum keyword declares a set of named integer constants; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no types. |
| CSS | Does not apply | Style rules have no types. |
| Regular expressions | Does not apply | A pattern has no types. |
The example files declare a Light enumeration with three values, print the name and the number of each value, and use a switch to find the next light.
| Language | Verdict | Form |
|---|---|---|
| Python | native | a subclass of enum.Enum; IntEnum and Flag for integer and flag enumerations7 |
| JavaScript | idiom | a frozen object of constants, or a set of string constants |
| TypeScript | native | enum, numeric or string; a union of string literal types is the common alternative9 |
| Java | native | enum, a class with a fixed set of instances56 |
| C | native | enum, a set of int constants2 |
| C++ | native | enum class (scoped) and plain enum (unscoped)10 |
| C# | native | enum, with an integral underlying type3 |
| Go | idiom | a named integer type and a const block with iota4 |
| Rust | native | enum; a variant can also carry data11 |
| Kotlin | native | enum class8 |
| PowerShell | native | enum in a script or a module |
| Bash | idiom | a set of string or integer constants |
| SQL | idiom | a CHECK constraint or a lookup table; some systems have an ENUM type |
| Regex | n/a | a pattern has no types |
| HTML/CSS | n/a | markup has no types; an HTML select element lists fixed choices |
C and C++. A plain C enum mixes freely with int. C++ added scoped enumerations, written enum class or enum struct.10 For a scoped enumeration, "There are no implicit conversions from the values of a scoped enumerator to integral types, although static_cast may be used to obtain the numeric value of the enumerator."10
TypeScript. "Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript."9 A numeric enum compiles to an object that maps names to numbers and numbers back to names; the handbook calls this a reverse mapping.9 The handbook also says: "In modern TypeScript, you may not need an enum when an object with as const could suffice".9 The example file uses such an object. Many programs also use a union of string literal types, such as "red" | "amber" | "green", in place of an enum.
Rust. The book says that "enums give you a way of saying a value is one of a possible set of values".11 A Rust enum whose variants carry no data is an enumeration. Its variants can also carry data, which makes it a full sum type.
from enum import Enum
class Light(Enum):
RED = 0
AMBER = 1
GREEN = 2
def after(light: Light) -> Light:
match light:
case Light.RED:
return Light.GREEN
case Light.GREEN:
return Light.AMBER
case Light.AMBER:
return Light.RED
for light in Light:
print(light.name.lower(), light.value, "then", after(light).name.lower())
print("by name:", Light["AMBER"].value, "by value:", Light(2).name.lower())
red 0 then green
amber 1 then red
green 2 then amber
by name: 1 by value: green
- Verdict: native. A subclass of
Enumlists its members as class attributes. Each member is an object with anameand avalue. - A loop over the class gives the members in definition order.
Light["AMBER"]looks a member up by name, andLight(2)looks it up by value.
#include <array>
#include <iostream>
#include <string_view>
enum class Light { Red, Amber, Green };
constexpr std::array<Light, 3> all{Light::Red, Light::Amber, Light::Green};
std::string_view name(Light l) {
switch (l) {
case Light::Red:
return "red";
case Light::Amber:
return "amber";
case Light::Green:
return "green";
}
return "no name";
}
Light after(Light l) {
switch (l) {
case Light::Red:
return Light::Green;
case Light::Green:
return Light::Amber;
case Light::Amber:
return Light::Red;
}
return Light::Red;
}
int main() {
for (Light l : all) {
std::cout << name(l) << ' ' << static_cast<int>(l) << " then " << name(after(l)) << '\n';
}
std::cout << "no name: " << name(static_cast<Light>(7)) << '\n';
}
red 0 then green
amber 1 then red
green 2 then amber
no name: no name
- Verdict: native. An
enum classis a scoped enumeration. Its names need the prefixLight::, and it does not convert tointby itself. static_castconverts to and from the number, so a value with no name is possible.- C++ cannot list the values of an enum, so the program keeps an
allarray.
import java.util.Locale;
public class Main {
enum Light {
RED, AMBER, GREEN;
Light after() {
return switch (this) {
case RED -> GREEN;
case GREEN -> AMBER;
case AMBER -> RED;
};
}
String lower() {
return name().toLowerCase(Locale.ROOT);
}
}
public static void main(String[] args) {
for (Light light : Light.values()) {
System.out.println(light.lower() + " " + light.ordinal() + " then " + light.after().lower());
}
System.out.println("by name: " + Light.valueOf("AMBER").ordinal());
}
}
red 0 then green
amber 1 then red
green 2 then amber
by name: 1
- Verdict: native. An
enumis a class with exactly one instance for each constant. It can have methods, such asafter. values()lists the constants in declaration order, andordinal()gives the position.- The
switchexpression covers every constant, so it needs nodefaultbranch.
#include <stdio.h>
enum light { RED, AMBER, GREEN };
static const char *const names[] = {"red", "amber", "green"};
static enum light after(enum light l) {
switch (l) {
case RED:
return GREEN;
case GREEN:
return AMBER;
case AMBER:
return RED;
}
return RED;
}
int main(void) {
for (int i = RED; i <= GREEN; i++) {
enum light l = (enum light)i;
printf("%s %d then %s\n", names[l], i, names[after(l)]);
}
printf("sum: %d\n", RED + AMBER + GREEN);
return 0;
}
red 0 then green
amber 1 then red
green 2 then amber
sum: 3
- Verdict: native. An
enumdeclares namedintconstants, here 0, 1 and 2. - C has no names at run time, so the program keeps an array of names in the same order.
- The constants are plain integers, so
RED + AMBER + GREENcompiles.
foreach (var light in Enum.GetValues<Light>())
{
Console.WriteLine($"{Lower(light)} {(int)light} then {Lower(After(light))}");
}
Console.WriteLine($"no name: {(Light)7}");
static Light After(Light light) => light switch
{
Light.Red => Light.Green,
Light.Green => Light.Amber,
Light.Amber => Light.Red,
_ => throw new ArgumentOutOfRangeException(nameof(light)),
};
static string Lower(Light light) => light.ToString().ToLowerInvariant();
enum Light { Red, Amber, Green }
red 0 then green
amber 1 then red
green 2 then amber
no name: 7
- Verdict: native. An
enumis a value type over an integral type,intby default. Enum.GetValues<Light>()lists the members. A cast converts between the enum and its number.- A cast can make a value with no name, such as
(Light)7, so theswitchneeds a_branch.
const Light = Object.freeze({ RED: 0, AMBER: 1, GREEN: 2 });
const nameOf = (value) => Object.keys(Light).find((k) => Light[k] === value).toLowerCase();
function after(light) {
switch (light) {
case Light.RED:
return Light.GREEN;
case Light.GREEN:
return Light.AMBER;
case Light.AMBER:
return Light.RED;
default:
throw new RangeError(`no light ${light}`);
}
}
for (const [name, value] of Object.entries(Light)) {
console.log(name.toLowerCase(), value, "then", nameOf(after(value)));
}
console.log("frozen:", Object.isFrozen(Light) ? "yes" : "no");
red 0 then green
amber 1 then red
green 2 then amber
frozen: yes
- Verdict: idiom. JavaScript has no enum. A frozen object maps names to values, and
Object.entrieslists them in insertion order. - Nothing stops a function from receiving a number that is not in the object, so
afterthrows for an unknown value. - String values, such as
"red", are also common, because they print well.
const Light = { Red: 0, Amber: 1, Green: 2 } as const;
type Light = (typeof Light)[keyof typeof Light]; // 0 | 1 | 2
const names = ["red", "amber", "green"] as const;
function after(light: Light): Light {
switch (light) {
case Light.Red:
return Light.Green;
case Light.Green:
return Light.Amber;
case Light.Amber:
return Light.Red;
}
}
for (const light of Object.values(Light)) {
console.log(`${names[light]} ${light} then ${names[after(light)]}`);
}
console.log("keys: " + Object.keys(Light).join(" "));
red 0 then green
amber 1 then red
green 2 then amber
keys: Red Amber Green
- Verdict: native. TypeScript has
enum, but an object withas constis often enough, and this example uses that form. as constkeeps the literal values, and the typeLightis the union0 | 1 | 2. A call such asafter(7)does not compile.- The
switchcovers every value, so the type checker acceptsafterwith no finalreturn.
package main
import "fmt"
type Light int
const (
Red Light = iota
Amber
Green
)
func (l Light) String() string {
switch l {
case Red:
return "red"
case Amber:
return "amber"
case Green:
return "green"
}
return fmt.Sprintf("Light(%d)", int(l))
}
func after(l Light) Light {
switch l {
case Red:
return Green
case Green:
return Amber
default:
return Red
}
}
func main() {
for l := Red; l <= Green; l++ {
fmt.Println(l, int(l), "then", after(l))
}
fmt.Println("no name:", Light(7))
}
red 0 then green
amber 1 then red
green 2 then amber
no name: Light(7)
- Verdict: idiom. Go has no enum keyword. A named integer type and a
constblock withiotagive the values 0, 1 and 2. - A
Stringmethod gives each value a name for printing. - Any integer converts to
Light, soLight(7)is a value with no name.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Light {
Red,
Amber,
Green,
}
impl Light {
const ALL: [Light; 3] = [Light::Red, Light::Amber, Light::Green];
fn name(self) -> &'static str {
match self {
Light::Red => "red",
Light::Amber => "amber",
Light::Green => "green",
}
}
fn after(self) -> Light {
match self {
Light::Red => Light::Green,
Light::Green => Light::Amber,
Light::Amber => Light::Red,
}
}
}
fn main() {
for light in Light::ALL {
println!("{} {} then {}", light.name(), light as i32, light.after().name());
}
println!("debug: {:?}", Light::Amber);
}
red 0 then green
amber 1 then red
green 2 then amber
debug: Amber
- Verdict: native. An
enumwhose variants carry no data is an enumeration.as i32gives the number of a variant. - A
matchmust cover every variant, sonameandafterneed no default branch. - Rust cannot list the variants of an enum, so the type declares an
ALLarray.
Variations and related ideas
- Flag enumerations. Each value is one bit, so a variable can hold a combination of values. In Python,
Flagmembers "support the bitwise operators & (AND), | (OR), ^ (XOR), and ~ (INVERT)".7 C# uses the[Flags]attribute for an enum whose members are bit fields.3 - String enumerations. The values are strings, not numbers. A TypeScript string enum gives "a meaningful and readable value when your code runs".9
- Enumerations with data. When a variant also carries values, the type is a sum type. See Sum types and Algebraic data type.
- Enumerations with methods. Java and Kotlin enum constants can have fields, constructors and methods, so each constant can carry fixed data such as a color code.58
- Booleans. A Boolean type is an enumeration with two values. See Boolean type.
Pitfalls
An integer enum can hold a value that has no name
In C, an enumeration variable has an integer type, so it can hold any number of that type. A switch that covers every name then misses the value.
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
enum light { RED, AMBER, GREEN };
static const char *light_name(enum light l) {
switch (l) {
case RED:
return "red";
case AMBER:
return "amber";
case GREEN:
return "green";
}
return "no name";
}
int main(void) {
enum light l = 7; /* compiles: the type is an integer type */
printf("%d %s\n", (int)l, light_name(l));
return 0;
}
7 no name
C# has the same rule. Its reference shows a cast of 0 to an enum that has no member for 0, and it uses Enum.IsDefined to check whether a value has a name.3 Code that reads an enumeration value from a file, a network or a database must check it.
A Python enum member is not equal to its value
A Python Enum member is an object, not a number. "Equality comparisons against non-enumeration values will always return False".12 Here the status comes from a database row as the number 1.
This code runs but gives a wrong answer on purpose.
from enum import Enum
class Status(Enum):
ACTIVE = 1
BLOCKED = 2
row_status = 1 # read from a database
print("active" if row_status == Status.ACTIVE else "not active")
not active
The fix is to convert the number first: Status(row_status) == Status.ACTIVE. IntEnum members are integers too, so they compare equal to numbers, but they lose the type check.7
Stored numbers depend on the order of the names
When the values come from the position of each name, as with C enums without explicit values or Go iota, a new name in the middle changes the numbers of the names after it.4 Numbers that were saved in a file or a database then mean different values. Give explicit values to any enumeration whose numbers leave the program, or store the names.
Cost
An integer enumeration costs the same as its underlying integer: one word or less, compared with one machine instruction. An object enumeration, as in Java or Python, stores a reference to one of a fixed set of objects. Comparison is a reference comparison. A switch on an enumeration with dense values can compile to a jump table.
History
Wikipedia notes that "While ALGOL 60 itself has no enumeration type, several languages descended from it do."1 In Pascal, a program can declare an enumerated type by "listing the values in a parenthesised list", as in (clubs, diamonds, hearts, spades).1 C has enum with integer constants.2 C++11 added scoped enumerations.10 Python added the enum module in version 3.4.7
References
- Enumerated type, Wikipedia, the introduction; Syntax by language, ALGOL 60 based languages
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.4.4.3 Enumeration constants; 6.7.2.2 Enumeration specifiers
- C# language reference, Enumeration types, the introduction; Enumeration types as bit flags; Conversions
- The Go Programming Language Specification, Iota
- The Java Tutorials, Enum Types, the whole page
- The Java Language Specification, Java SE 21 Edition, 8.9 Enum Classes, 8.9
- The Python Standard Library, enum, the introduction; IntEnum; Flag
- Kotlin documentation, Enum classes, the introduction; Working with enum constants
- TypeScript Handbook, Enums, the introduction; Reverse mappings
- cppreference.com, Enumeration declaration, Scoped enumerations
- The Rust Programming Language, 6.1 Defining an Enum, the introduction
- Python HOWTOs, Enum HOWTO, Comparisons
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag DS22BP Edit this page History Report an error Markdown