📦 C++ Arrays & Structures
Estimated reading: 4 minutes 276 views

Here’s a complete and SEO-optimized article on C++ Enums and Enum Class, including examples, differences, use cases, best practices, and FAQ:


C++ Enums & enum class – Strongly-Typed Constants in C++


Introduction – Why Learn C++ Enums?

In C++ programming, enums (enumerations) are used to define a set of named integral constants that make code more readable and less error-prone. The modern enum class introduced in C++11 further improves type safety, preventing unintended conversions and name conflicts.

In this guide, you’ll learn:

  • What is an enum and enum class
  • Syntax and usage examples
  • Enum vs enum class comparison
  • Use cases in real-world projects
  • Best practices and common pitfalls

Core Concept – What is an Enum in C++?

An enum defines a group of related constant integer values using identifiers.

enum Color { RED, GREEN, BLUE };

By default:

  • RED = 0, GREEN = 1, BLUE = 2
  • Enums are of type int unless specified otherwise.

Code Examples – With Explanation

Example 1: Basic Enum Usage

#include <iostream>
using namespace std;

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

int main() {
    Direction d = East;
    cout << "Direction: " << d << endl; // Output: 2
    return 0;
}

Explanation:

  • East is the 3rd element (index 2)
  • Enums are implicitly convertible to int

Example 2: Enum with Assigned Values

enum Status {
    OK = 200,
    NOT_FOUND = 404,
    SERVER_ERROR = 500
};

Useful when mapping enums to HTTP status codes or error values.


Example 3: enum class (Scoped Enum)

#include <iostream>
using namespace std;

enum class State { Idle, Running, Stopped };

int main() {
    State s = State::Running;

    if (s == State::Running) {
        cout << "System is active.\n";
    }

    return 0;
}

Why Use enum class?

  • Scoped ➝ no global name pollution
  • Strongly typed ➝ prevents implicit conversion to int

Best Practices & Tips

Best Practices:

  • Use enum class for type safety and clarity
  • Specify underlying type (enum class Mode : uint8_t { ... };) for memory control
  • Use switch statements with default to catch unhandled enum cases

Tips:

  • For readable output, use std::map or std::unordered_map for enum-to-string conversion
  • Create utility functions for string mapping if enum values are user-facing

Common Pitfalls:

  • Using traditional enums causes naming collisions in global scope
  • Mixing enums from different domains accidentally (e.g., Color == Direction)
  • Forgetting to handle all enum values in switch can lead to bugs

Enum vs Enum Class – Comparison Table

Featureenum (Traditional)enum class (Scoped Enum)
ScopeGlobalLocal to the enum
Type Safety Not type-safe Strongly typed
Implicit Conversion Converts to int Requires explicit cast
Duplicate IdentifiersPossible (causes conflicts)Not allowed (must use scope)
Use CaseLegacy codeModern, safer C++ code

Use Cases & Industry Applications

Where to Use Enums:

  • State machines (e.g., game or device states)
  • HTTP status codes
  • Day of the week, months
  • Error handling and logging levels
  • User permissions or roles

Summary – Recap & Next Steps

C++ enums and enum class help organize and manage fixed sets of constants, enhancing code readability and maintainability.

Key Takeaways:

  • Use traditional enum for backward compatibility
  • Prefer enum class for type-safe, scoped enumerations
  • Always handle all possible enum values in control statements

Next Steps:

  • Explore std::variant or std::optional with enums
  • Learn how to implement enum-to-string mapping
  • Use enums inside classes or namespaces for clean architecture

FAQ Section

What is the default type of C++ enum?

int is the default underlying type unless explicitly specified.


Can enum values be printed directly?

Yes, but it prints the underlying integer. Use custom mapping for strings.

cout << Color::RED; // Prints 0

How to convert enum class to int?

int val = static_cast<int>(State::Running);

You must use static_cast because enum class is strongly typed.


Can enums be used in switch statements?

Yes, both enum and enum class can be used, but enum class requires static_cast or fully qualified names.


Can I assign custom values to enum class members?

Yes.

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

Share Now :
Share

C++ Enums – Enum Class

Or Copy Link

CONTENTS
Scroll to Top