Skip to content

Enums#

Enums (from "enumerable") allow us to create data types with finitely many possible values (variants), each of which we want to give a specific name.

The syntax for the declaration of an enum type is the following

enum-specifier:
    enum identifieropt { enumerator-list }
    enum identifieropt { enumerator-list , }
    enum identifier

enumerator-list:
    enumerator
    enumerator-list , enumerator

enumerator:
    enumeration-constant
    enumeration-constant = constant-expression

Example

Here an example declaration of an enum type:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };

To declare variables we use the following syntax:

enum Day day1, day2;

We can also merge the two:

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } day1, day2;

For assignment, we use the enum variants directly:

day1 = Monday;
day2 = Tuesday;

Internally, an enum is represented as an integer and enum variants are represented as integer literals. You can change the representation of a specific variant by assigning it a value in the enum declaration. All variants thar do not have representations assigned explicitly get assigned numbers in increasing order, starting at zero.