Skip to content

enum class (C++11)

In a Nutshell

A scoped enumeration type that resolves the issues of traditional enum polluting the global namespace and implicitly converting to integers.

None required (language keyword)

Core API Quick Reference

OperationSignatureDescription
Declarationenum class Name { A, B, C };Basic scoped enumeration, default underlying type is int
Specify underlying typeenum class Name : uint8_t { A, B };Fixed underlying type, saves memory
Access enumeratorName::AMust be accessed via the scope operator
Convert to integerstatic_cast<int>(Name::A)Requires explicit cast, no implicit conversion
Opaque declarationenum class Name : uint8_t;Forward declaration, requires specifying the underlying type
using enumusing enum Name;(C++20) Introduces enumerators into the current scope

Minimal Example

cpp
// Standard: C++11
#include <iostream>

int main() {
    enum class Color : uint8_t { red, green = 20, blue };
    Color r = Color::blue;

    switch (r) {
        case Color::red:   std::cout << "red\n";   break;
        case Color::green: std::cout << "green\n"; break;
        case Color::blue:  std::cout << "blue\n";  break;
    }

    // int n = r; // error
    int n = static_cast<int>(r);
    std::cout << n << '\n'; // 21
}

Embedded Applicability: High

  • Specifying the underlying type (e.g., uint8_t, uint32_t) allows precise control over memory footprint, ideal for protocol parsing and register mapping
  • Zero runtime overhead, fully resolved at compile time
  • Eliminates naming conflicts, suitable for modular development in large embedded projects
  • Explicit type conversions prevent accidental integer comparisons, improving code safety

Compiler Support

GCCClangMSVC
4.73.12010

See Also


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

Built with VitePress