Enum in C++

An enum in C++ is a user-defined type that represents a fixed set of named integral constants. Instead of writing raw numbers like 0, 1, and 2 throughout a program, you can give those values meaningful names such as Sunday, Monday, and Tuesday. This makes code easier to read, easier to maintain, and less error-prone.

Enums are commonly used when a variable should only hold one value from a small, known group. Typical examples include menu choices, application states, weekdays, directions, status codes, and modes of operation. In C++, the traditional enum is often called an unscoped enumeration. Modern C++ also has enum class, which is a related but stricter feature. In this article, we will focus on ordinary enum in C++ and briefly note how it differs from enum class.

What Is Enum in C++?

An enum is a custom type whose possible values are represented by named constants called enumerators. Each enumerator is associated with an integral value. If you do not assign values manually, C++ starts from 0 and increases by 1 for the following items.

enum Day
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday
};

In this example, Sunday has value 0, Monday has value 1, Tuesday has value 2, and Wednesday has value 3.

EnumeratorDefault Integral Value
Sunday0
Monday1
Tuesday2
Wednesday3

An enum gives names to a small set of integer-based choices. The names improve meaning, even though the underlying representation is still integral.

Why Enum Is Used in C++

  • It replaces unclear magic numbers with meaningful names.
  • It limits a variable to a small known set of logical values.
  • It improves readability in conditions, switch statements, and state handling.
  • It groups related constants under one logical type.
  • It makes maintenance easier when the program uses fixed categories or modes.

Suppose a program stores traffic signal states as 0, 1, and 2. Someone reading the code later must remember what each number means. But if the code uses Red, Yellow, and Green, the meaning becomes clear immediately. That is the practical strength of enums.

Syntax of Enum in C++

The basic syntax of an enum is straightforward. You write the keyword enum, then the enum type name, followed by a list of enumerators inside braces.

enum Color
{
    Red,
    Green,
    Blue
};

After this declaration, Color becomes a type, and Red, Green, and Blue become enumerators associated with integer values.

How to Declare and Use an Enum Variable

Once the enum type is declared, you can create variables of that type and assign one of the enumerators to them.

enum Direction
{
    North,
    South,
    East,
    West
};

int main()
{
    Direction move = East;
    return 0;
}

Here, move is an enum variable of type Direction, and it stores the enumerator East. This is clearer than storing some unrelated number and trying to remember what it means.

Default Values of Enum Members in C++

If you do not assign values explicitly, C++ gives the first enumerator value 0 and continues increasing by 1.

Enum DeclarationResulting Values
enum Level { Low, Medium, High };Low = 0, Medium = 1, High = 2

This automatic numbering is often enough when you only need symbolic names. But C++ also lets you assign your own values when required.

Assigning Custom Values to Enum Members

You can assign explicit integral values to enumerators. This is useful for protocol values, bit flags, menu codes, device commands, and any case where the numeric meaning matters.

enum StatusCode
{
    Success = 200,
    NotFound = 404,
    ServerError = 500
};

When you assign one value manually, the following unassigned enumerators continue from there.

enum Code
{
    A = 10,
    B,
    C
};

In this example, B becomes 11 and C becomes 12.

EnumeratorAssigned or Deduced Value
A10
B11
C12

Enum Values Are Integral in C++

Although enums create a new type, the enumerators are still integral constants underneath. That is why you can print them as numbers or use them in integral expressions when needed.

#include <iostream>

enum Day
{
    Sunday,
    Monday,
    Tuesday
};

int main()
{
    Day today = Monday;
    std::cout << today << std::endl;
    return 0;
}

This program prints the underlying numeric value of Monday, which is 1 in this case. That behavior helps explain that enum names are symbolic labels for integral values.

Using Enum in Switch Statements

Enums are especially useful with switch statements because each named choice reads naturally and avoids raw integers in branch logic.

#include <iostream>

enum TrafficLight
{
    Red,
    Yellow,
    Green
};

int main()
{
    TrafficLight signal = Green;

    switch (signal)
    {
        case Red:
            std::cout << "Stop" << std::endl;
            break;
        case Yellow:
            std::cout << "Wait" << std::endl;
            break;
        case Green:
            std::cout << "Go" << std::endl;
            break;
    }

    return 0;
}

This is one of the cleanest real-world patterns for enums. The type describes the allowed states, and the switch statement handles them by name.

Enum vs const int or Macros in C++

Before enums are understood well, beginners often use multiple integer constants or even macros for related choices. But enums communicate structure better because they define one logical type for a related set of values.

ApproachExampleIssue or Benefit
Raw numbersint state = 2;Meaning is unclear
const int valuesconst int Green = 2;Better naming, but weaker grouping
Macro#define GREEN 2No type safety and poor scoping
Enumenum TrafficLight { Red, Yellow, Green };Clear grouping and named integral constants

An enum does not solve every safety issue in the old unscoped form, but it still expresses intent much better than scattered integer constants.

Common Uses of Enum in C++ Programs

  • Days of the week
  • Months of the year
  • Directions such as north, south, east, and west
  • Menu choices in console applications
  • Traffic signal states
  • Game states such as start, pause, win, and lose
  • Status and error codes in embedded or systems programs

If the values represent a closed set of named options, then enum is often a good candidate.

Common Mistakes with Enum in C++

  • Assuming enums store text strings instead of integral values.
  • Forgetting that unscoped enum names enter the surrounding scope.
  • Mixing unrelated enum values just because the underlying type is integral.
  • Using enums for values that do not really form a fixed closed set.
  • Expecting std::cout to print the enumerator name automatically instead of the numeric value.

That last mistake is especially common. If you want friendly text output like Green instead of 2, you usually write your own conversion logic with a switch statement or helper function.

Enum and Name Conflicts in C++

Traditional enums in C++ are unscoped. That means the enumerator names like Red or Green are placed directly into the surrounding scope. If another enum or variable uses the same names, conflicts can happen.

This is one of the reasons modern C++ introduced enum class. But for ordinary enum, you should choose enumerator names carefully to avoid collisions in larger programs.

Enum vs Enum Class in C++

Ordinary enum and enum class are related, but they are not the same. An ordinary enum is unscoped and more permissive. An enum class is scoped and stricter, which improves type safety and prevents many naming conflicts.

Featureenumenum class
Scope of enumerator namesNames enter the surrounding scopeNames stay inside the enum type scope
Implicit conversion to integerMore permissiveMore restricted
Type safetyLowerHigher

Since the next topic is specifically Enum Class in C++, that subject deserves its own full explanation. For now, the main point is that ordinary enums are simpler and older, while enum classes are stricter and often preferred in modern code when stronger scoping is needed.

How to Print Friendly Enum Names in C++

By default, printing an enum variable with std::cout usually prints its underlying numeric value rather than the symbolic name. If you want readable output such as Green or Monday, you typically write a helper function that converts the enum value into text. This is a common pattern in debugging, menus, status messages, and logs.

const char* toText(TrafficLight signal)
{
    switch (signal)
    {
        case Red:    return "Red";
        case Yellow: return "Yellow";
        case Green:  return "Green";
    }

    return "Unknown";
}

This keeps the enum itself simple while still giving the program human-friendly display text where needed.

Underlying Values and Ordering in Enum

Because enum members are integral underneath, they can be compared and ordered according to their underlying values. That means an enum can sometimes represent priority levels, stages, or modes that naturally progress from one value to another. Still, this should be done only when the numeric ordering actually has logical meaning in the domain. If the values are just labels, comparing them as numbers can make code less clear.

For example, if an enum represents severity as Low, Medium, and High, numeric ordering can make sense. But if an enum represents unrelated states such as Start, Pause, and Exit, treating them as ordered numbers may not communicate good intent.

Best Practices for Using Enum in C++

  • Use enums for fixed groups of related named choices.
  • Prefer meaningful enumerator names that explain domain intent clearly.
  • Assign explicit values only when the numeric meaning matters.
  • Use helper logic if you need friendly text output.
  • Consider enum class when stronger scoping and type safety are important.

Frequently Asked Questions about Enum in C++

Is enum in C++ a data type?

Yes. An enum creates a user-defined type whose values come from a fixed set of named integral constants.

Does enum store strings in C++?

No. Enum values are represented as integral constants, not strings. The names are for the programmer, while the stored form is integer-based.

Can I assign custom values to enum members?

Yes. You can assign explicit integral values to some or all enumerators depending on your program needs.

Why is enum better than using raw numbers?

Because enums give names to those numbers, which makes the code clearer and easier to maintain.


Continue learning C++ in order
Follow the topic sequence with the previous and next lesson.