• Home
  • 1.23 Enumerations

1.23 Enumerations

View Categories

1.23 Enumerations

< 1 min read

Table of Contents

An enumeration is a user-defined data type that represents a fixed set of named integral constants. Enumerations improve code readability by allowing meaningful names to be used instead of numeric values.

Each enumerator is assigned an integer value. By default, the first enumerator has the value 0, and each subsequent enumerator is assigned the next integer value unless explicitly specified.

Source Code #

#include <iostream>

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

int main()
{
    Day today = Wednesday;

    std::cout << "Numeric value: " << today << '\n';

    return 0;
}

Output #

Numeric value: 3

Explanation #

  • The enum keyword defines a user-defined enumeration type named Day.
  • Each identifier inside the enumeration is called an enumerator.
  • By default, the first enumerator (Sunday) is assigned the value 0.
  • Each subsequent enumerator is assigned the next consecutive integer value.
  • Day today = Wednesday; declares a variable of type Day and initializes it with the enumerator Wednesday.
  • When an enumeration variable is sent to std::cout, its underlying integer value is printed.
  • Enumerations make programs easier to read by replacing numeric constants with descriptive names.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *