Topic 39 of 91 7. C++ Structures and Unions Interactive Tutorial

Enumerations in C++: Defining Named Constant Values With enum

13 mins read Last updated: 26 Sep 2026 19,400 views

Direct Answer & Core Concept

In C++, programs often work with a fixed set of related values. For example, an application may need to represent days of the week, months, traffic light signals, payment statuses, or user roles.

You could use integers or strings to represent these values, but doing so can make programs harder to understand and maintain.

C++ provides a feature called enumeration (enum) that allows you to define a collection of named constant values.

For example, instead of writing 1, 2, and 3 to represent different order statuses, you can define meaningful names such as Pending, Processing, and Completed.

Detailed Explanation & Mechanics

1. What Is an Enumeration in C++?

An enumeration is a user-defined type that represents a set of named constant values.

Each name is called an enumerator.

Syntax

main.cpp
Run Online
enum EnumName {
    VALUE1,
    VALUE2,
    VALUE3
};

Here:

  • enum is the keyword used to declare an enumeration.

  • EnumName is the name of the enumeration type.

  • VALUE1, VALUE2, and VALUE3 are enumerators.

  • The semicolon after the closing brace is required.

Example: Declare an Enumeration

main.cpp
Run Online
#include <iostream>
using namespace std;

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

int main() {
    Day today = Wednesday;

    cout << today;

    return 0;
}

Output:

By default, the first enumerator has the value 0, and each following enumerator increases by one.

EnumeratorDefault value
Monday0
Tuesday1
Wednesday2
Thursday3
Friday4
Saturday5
Sunday6

The output is 2 because Wednesday has the underlying value 2.

Although the value can be displayed as an integer, using meaningful enumerator names makes the program easier to read.

2. Declaring and Initializing enum Variables

After defining an enumeration, you can create variables of that type.

Syntax

Example:

main.cpp
Run Online
enum Color {
    Red,
    Green,
    Blue
};

Color selectedColor = Green;

Here, selectedColor is an enumeration variable containing the value Green.

You can also assign another enumerator:

A traditional unscoped enum can also be declared and used directly:

main.cpp
Run Online
enum Status {
    Pending,
    Approved,
    Rejected
};

Status orderStatus = Pending;

3. Assigning Custom Values to Enumerators

By default, enumerators receive consecutive integer values starting from zero. You can also assign your own values.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

enum Level {
    Low = 1,
    Medium = 5,
    High = 10
};

int main() {
    Level currentLevel = High;

    cout << "Level value: " << currentLevel;

    return 0;
}

Output:

In this example:

  • Low has the value 1.

  • Medium has the value 5.

  • High has the value 10.

If an enumerator is not explicitly assigned a value, it normally receives one greater than the previous enumerator.

Example:

main.cpp
Run Online
enum Number {
    First = 10,
    Second,
    Third,
    Fourth = 20,
    Fifth
};

The values are:

EnumeratorValue
First10
Second11
Third12
Fourth20
Fifth21

4. Using enum With switch Statements

Enumerations work particularly well with switch statements because each enumerator represents a named option.

Example: Display Days of the Week

main.cpp
Run Online
#include <iostream>
using namespace std;

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

int main() {
    Day today = Friday;

    switch (today) {
        case Monday:
            cout << "Start of the working week";
            break;

        case Friday:
            cout << "End of the working week";
            break;

        case Saturday:
        case Sunday:
            cout << "Weekend";
            break;

        default:
            cout << "Regular working day";
    }

    return 0;
}

Output:

The switch statement checks the enumeration value and executes the matching case.

Using named values is clearer than writing numeric case labels such as 0, 1, or 2.

5. Comparing enum Values

You can compare values of the same enumeration type using comparison operators.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

enum Priority {
    Low,
    Medium,
    High
};

int main() {
    Priority task = High;

    if (task == High) {
        cout << "High priority task";
    } else {
        cout << "Other priority";
    }

    return 0;
}

Output:

You can use operators such as:

  • == for equality.

  • != for inequality.

  • < for less than.

  • > for greater than.

  • <= for less than or equal to.

  • >= for greater than or equal to.

These comparisons use the enumerators' underlying values. Use them only when the numeric ordering is meaningful for your application.

6. What Is enum class in C++?

C++11 introduced scoped enumerations, declared using enum class or enum struct.

They provide stronger type safety and avoid placing enumerator names directly into the surrounding scope.

Syntax

main.cpp
Run Online
enum class EnumName {
    VALUE1,
    VALUE2,
    VALUE3
};

Example: Using enum class

main.cpp
Run Online
#include <iostream>
using namespace std;

enum class Color {
    Red,
    Green,
    Blue
};

int main() {
    Color selectedColor = Color::Green;

    if (selectedColor == Color::Green) {
        cout << "Green color selected";
    }

    return 0;
}

Output:

Notice the syntax:

With enum class, you must qualify enumerators using the enumeration type name.

Advantages of enum class

  1. Provides stronger type safety.

  2. Keeps enumerator names inside their enumeration scope.

  3. Prevents implicit conversion to integers.

  4. Reduces accidental name conflicts.

  5. Makes code easier to understand in larger applications.

For most new C++ code, enum class is generally the preferred choice.

7. Difference Between enum and enum class

Traditional unscoped enums and scoped enums have some important differences.

Featureenumenum class
IntroducedTraditional C++C++11
Enumerator scopeSurrounding scopeEnumeration scope
Implicit conversion to integerSupportedNot supported
Type safetyLess restrictiveStronger
Name conflictsMore likelyLess likely
Access syntaxRedColor::Red
Underlying typeImplementation-selected integral typeImplementation-selected integral type

Example: Traditional enum

main.cpp
Run Online
enum Color {
    Red,
    Green,
    Blue
};

Color selected = Green;
int value = selected;

The conversion to int is allowed.

Example: enum class

main.cpp
Run Online
enum class Color {
    Red,
    Green,
    Blue
};

Color selected = Color::Green;

// int value = selected; // Compilation error

You must explicitly convert a scoped enumerator when an integer value is needed.

main.cpp
Run Online
int value = static_cast<int>(selected);

8. Specifying the Underlying Type of an Enumeration

C++ allows you to specify the integral type used to represent an enumeration.

This is useful when you need a particular representation or a defined range.

Syntax

main.cpp
Run Online
enum class EnumName : data_type {
    VALUE1,
    VALUE2
};

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

enum class Status : unsigned char {
    Pending = 1,
    Approved = 2,
    Rejected = 3
};

int main() {
    Status current = Status::Approved;

    cout << static_cast<int>(current);

    return 0;
}

Output:

Here, unsigned char is the specified underlying type.

The explicit conversion is needed because enum class values do not automatically convert to integers.

You can also specify an underlying type for a traditional enum:

main.cpp
Run Online
enum Status : unsigned char {
    Pending = 1,
    Approved = 2,
    Rejected = 3
};

9. Forward Declaration of an enum

A scoped enumeration can be declared before its full definition, provided its underlying type is known or specified as required by the language rules.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

enum class Status : int;

void displayStatus(Status value);

enum class Status : int {
    Pending,
    Approved,
    Rejected
};

void displayStatus(Status value) {
    if (value == Status::Approved) {
        cout << "Approved";
    }
}

int main() {
    displayStatus(Status::Approved);

    return 0;
}

Output:

Forward declarations are useful when organizing declarations across multiple source files or headers.

10. Using enum for Bit Flags

Enumerations can also represent sets of independent options using bit flags.

This is commonly done with scoped enumerations and bitwise operators.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

enum class Permission : unsigned int {
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4
};

int main() {
    Permission access =
        static_cast<Permission>(
            static_cast<unsigned int>(Permission::Read) |
            static_cast<unsigned int>(Permission::Write)
        );

    unsigned int flags = static_cast<unsigned int>(access);

    if ((flags & static_cast<unsigned int>(Permission::Read)) != 0) {
        cout << "Read permission enabled" << endl;
    }

    if ((flags & static_cast<unsigned int>(Permission::Write)) != 0) {
        cout << "Write permission enabled" << endl;
    }

    if ((flags & static_cast<unsigned int>(Permission::Execute)) != 0) {
        cout << "Execute permission enabled" << endl;
    }

    return 0;
}

Output:

main.cpp
Run Online
Read permission enabled
Write permission enabled

Each flag uses a different bit:

PermissionValueBinary representation
None0000
Read1001
Write2010
Execute4100

The bitwise OR operation combines permissions. The bitwise AND operation checks whether a particular flag is present.

For larger applications, you can define overloaded bitwise operators to make flag handling easier to read.

11. Using enum in Functions

Enumeration values can be passed to functions like other variables.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

enum class TrafficLight {
    Red,
    Yellow,
    Green
};

void displaySignal(TrafficLight signal) {
    switch (signal) {
        case TrafficLight::Red:
            cout << "Stop";
            break;

        case TrafficLight::Yellow:
            cout << "Get Ready";
            break;

        case TrafficLight::Green:
            cout << "Go";
            break;
    }
}

int main() {
    displaySignal(TrafficLight::Green);

    return 0;
}

Output:

Using an enumeration as a function parameter makes the expected set of values clear.

12. Using enum in Structures and Classes

Enumerations can be used as data members in structures and classes.

Example: Employee Department

main.cpp
Run Online
#include <iostream>
#include <string>
using namespace std;

enum class Department {
    HR,
    IT,
    Finance,
    Sales
};

struct Employee {
    int id;
    string name;
    Department department;
};

int main() {
    Employee emp = {
        101,
        "Amit",
        Department::IT
    };

    cout << "Employee ID: " << emp.id << endl;
    cout << "Employee Name: " << emp.name << endl;

    if (emp.department == Department::IT) {
        cout << "Department: IT";
    }

    return 0;
}

Output:

main.cpp
Run Online
Employee ID: 101
Employee Name: Amit
Department: IT

This approach is useful when records need to store values selected from a fixed set of options.

13. enum vs const vs constexpr

C++ provides several ways to represent constant values. They serve different purposes.

Featureenumconstconstexpr
Main purposeDefine named related valuesPrevent modification of an object through that nameDefine values usable in constant expressions when initialized appropriately
Multiple related valuesYesIndividual declarationsIndividual declarations or related constants
User-defined typeYesNoNo
Type safetyStronger with enum classDepends on declared typeDepends on declared type
Common useStatus, category, directionValues that must not be modifiedCompile-time constants

Example: const

Example: constexpr

main.cpp
Run Online
constexpr int maxSize = 50;

Example: enum class

main.cpp
Run Online
enum class Status {
    Pending,
    Approved,
    Rejected
};

Use an enumeration when you have a fixed group of named alternatives. Use const or constexpr for individual constant values.

14. Real-World Applications of Enumerations in C++

Enumerations are useful in many software applications.

Order Management Systems

Represent order states such as Pending, Processing, Shipped, and Delivered.

Banking Applications

Represent transaction types such as Deposit, Withdrawal, and Transfer.

Game Development

Represent game states, player actions, directions, and difficulty levels.

Traffic Control Systems

Represent traffic light states such as Red, Yellow, and Green.

Employee Management Systems

Represent departments, employment types, or role categories.

Network Applications

Represent connection states, request types, and protocol options.

15. Common Mistakes When Using enum

Mistake 1: Using an Enumerator Outside Its Scope

With enum class, this is incorrect:

main.cpp
Run Online
enum class Color {
    Red,
    Green
};

Color selected = Green; // Compilation error

Use the qualified name:

main.cpp
Run Online
Color selected = Color::Green;

Mistake 2: Assigning an Integer Directly to enum class

Incorrect:

main.cpp
Run Online
enum class Status {
    Pending,
    Approved
};

Status current = 1; // Compilation error

Use a named enumerator:

main.cpp
Run Online
Status current = Status::Approved;

If you genuinely need a conversion, use an explicit cast after validating the value.

Mistake 3: Assuming Enumerator Values Always Start From Zero

An unscoped or scoped enumeration can use explicitly assigned values.

main.cpp
Run Online
enum Status {
    Pending = 10,
    Approved = 20,
    Rejected = 30
};

Do not assume the first value is always zero.

Mistake 4: Reusing Enumerator Names in the Same Scope

Traditional unscoped enums introduce their enumerator names into the surrounding scope. Reusing the same name can cause a compilation error.

Using enum class helps avoid this problem.

Mistake 5: Using enum When a Dynamic Set Is Needed

An enumeration is appropriate for a fixed set of named alternatives. If values need to be created dynamically at runtime, a different data structure may be more suitable.

16. Best Practices for Using Enumerations

  1. Prefer enum class for new C++ code.

  2. Use meaningful enumerator names.

  3. Specify an underlying type when a particular representation is required.

  4. Avoid relying on implicit integer conversions.

  5. Use switch statements to handle distinct enumeration values.

  6. Include a suitable default or handle all expected cases.

  7. Use distinct powers of two for bit flags.

  8. Avoid using raw numeric values when named enumerators are available.

  9. Keep enumeration definitions close to the types and functions that use them.

  10. Use enumerations for fixed sets of related values, not arbitrary user-generated data.

17. Frequently Asked Questions (FAQs)

1. What is an enum in C++?

An enum is a user-defined type that defines a set of named constant values.

2. Which keyword is used to declare an enumeration?

The enum keyword is used to define an enumeration in C++.

3. What is the default starting value of an enum?

The first enumerator has the value 0 by default. Each subsequent enumerator normally receives a value one greater than the previous one.

4. Can we assign custom values to enum members?

Yes. You can assign explicit integral values to enumerators.

5. What is enum class in C++?

enum class is a scoped, strongly typed enumeration introduced in C++11. It prevents enumerator names from being injected into the surrounding scope and does not implicitly convert to integers.

6. What is the difference between enum and enum class?

Traditional enum values are unscoped and can implicitly convert to integers. enum class values are scoped and require explicit conversion when an integer is needed.

7. Can we use enum with switch statements?

Yes. Both traditional enums and scoped enums can be used in switch statements.

8. Can we compare enum values?

Yes. Values of the same enumeration type can be compared using operators such as ==, !=, <, and >.

9. Can an enum have a custom underlying type?

Yes. You can specify an integral type:

main.cpp
Run Online
enum class Status : unsigned char {
    Pending,
    Approved
};

10. Can we use enum inside a structure?

Yes. An enumeration can be used as a data member in a structure or class.

11. Can enum be used for bit flags?

Yes. Enumerations can represent independent bit flags using powers of two and bitwise operations.

12. Which is better: enum or enum class?

For most modern C++ programs, enum class is preferred because it provides better scope control and stronger type safety.

Runnable Code Example: Enumerations in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <cstdint>

// Scoped enum with explicit underlying type uint8_t
enum class NetworkState : uint8_t {
    Disconnected = 0,
    Connecting = 1,
    Connected = 2,
    Error = 255
};

void checkState(NetworkState state) {
    if (state == NetworkState::Connected) {
        std::cout << "Network is healthy and connected.
";
    } else {
        std::cout << "Network state code: " << static_cast<int>(state) << "
";
    }
}

int main() {
    NetworkState current = NetworkState::Connected;
    checkState(current);

    NetworkState err = NetworkState::Error;
    checkState(err);

    std::cout << "Enum storage size: " << sizeof(current) << " byte
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: Why are enum class types preferred over traditional C-style enums in C++?

A: Scoped `enum class` types prevent namespace collisions (e.g. two enums defining `RED`), forbid accidental implicit conversion to integers, and allow explicit specification of underlying storage sizes (e.g. `: uint8_t`).
Q

Q: Can an enum class have an underlying type of int64_t?

A: Yes. Any integral type can be specified: `enum class BigId : int64_t { ... }`.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Always use `enum class` instead of unscoped `enum`. 2. Specify small underlying types (e.g. `: uint8_t`) to save memory when enumerators are small. 3. Use `static_cast(e)` when numeric serialization is necessary.