Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

C++ Enum: How to Declare and Use Enums

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

An enum (enumeration) in C++ lets you define a type whose values are a fixed set of named constants, so code reads as Color::Red instead of a bare 0. Declare one with enum class Color { Red, Green, Blue }; and use it with the scope operator. That single line gives you type safety, readable names, and a compiler that catches invalid assignments. This guide walks through declaring, using, and troubleshooting enums in modern C++.

What You'll Need

  • A C++ compiler that supports C++11 or later (GCC, Clang, or MSVC). Scoped enums (enum class) require C++11.
  • A text editor or IDE to write and save .cpp source files.
  • Basic familiarity with compiling and running a C++ program (for example, g++ main.cpp -o main).
  • Optionally, a build system like CMake if you are adding enums to a larger project.

Step-by-Step

  1. Choose scoped or unscoped. Prefer enum class (scoped) for new code. It keeps enumerator names inside the enum's scope, prevents implicit conversion to integers, and avoids name clashes. Use plain enum (unscoped) only when you need implicit integer conversion or are matching an existing C API.
  2. Declare the enum. Write enum class Color { Red, Green, Blue }; at namespace or class scope. By default the first enumerator is 0, the next is 1, and so on. You can set values explicitly: enum class Status { Ok = 200, NotFound = 404 };.
  3. Choose an underlying type when it matters. For scoped enums the default underlying type is int. If you need a specific size or a fixed layout (for example, for serialization or interop), write enum class Flags : unsigned char { A = 1, B = 2 };. The underlying type must be an integral type.
  4. Use the enumerators. With a scoped enum, qualify each name: Color c = Color::Red;. With an unscoped enum declared at namespace scope, you write Color c = Red;. Mixing them up is a common compile error.
  5. Compare and switch. Enums work naturally in switch statements: switch (c) { case Color::Red: /* ... */ break; default: break; }. The compiler can warn when you miss a case if you enable warnings (for example, -Wswitch with GCC or Clang).
  6. Convert to and from integers deliberately. Scoped enums do not convert implicitly. Use static_cast<int>(c) to get the numeric value, and static_cast<Color>(n) to go back. Validate n before casting, because the compiler will not check that it matches a real enumerator.
  7. Iterate over enumerators if needed. C++ has no built-in reflection for enums, so iteration requires either a sentinel value (for example, Count as the last enumerator) and a loop from 0 to Count - 1, or an explicit array of the values you care about. Keep the sentinel out of switch logic.
  8. Compile and test. Build with warnings enabled (-Wall -Wextra for GCC/Clang, /W4 for MSVC). Fix any warnings about unhandled cases or narrowing conversions before moving on.

Common Mistakes

  • Forgetting the scope operator. Writing Color c = Red; with a scoped enum fails to compile. Use Color::Red.
  • Assuming implicit integer conversion. Scoped enums will not convert to int in arithmetic or when passed to functions expecting an integer. Cast explicitly.
  • Name collisions in unscoped enums. Two unscoped enums in the same scope cannot both define Unknown. Scoped enums avoid this.
  • Casting unchecked values. static_cast<Color>(99) compiles but produces a value that matches no enumerator. Validate input first.
  • Using an enum as a bitmask without operators. Plain enums do not support |, &, or ~ out of the box. Either define those operators yourself or use std::bitset/integer flags.
  • Relying on the numeric values. Unless you assign values explicitly, the numbers are an implementation detail of your declaration order. Do not serialize them without pinning values.

Tips

  • Name the enum in the singular (Color, not Colors) and enumerators in a consistent style, such as PascalCase or UPPER_SNAKE.
  • Put enums in a header if multiple translation units need them, and include that header where used.
  • Use enum class inside a class to group related constants without polluting the enclosing namespace.
  • For serialization, assign explicit values and document them; this keeps file formats stable if you reorder enumerators later.
  • Enable compiler warnings for switch statements so a new enumerator triggers a warning in every switch that does not handle it.
  • Do not use enums for values that change at runtime or come from user input; validate and map to an enum at the boundary.

Troubleshooting

If your code does not compile, start with the error message. "Red was not declared in this scope" usually means you used an unscoped name with a scoped enum, or forgot to include the header. "Cannot convert Color to int" means you need static_cast<int>. "Redeclaration of enumerator" means two unscoped enums share a name in the same scope; rename one or switch to enum class. If a switch warns about an unhandled case, either add the case or add a default label deliberately. If a value cast from an integer behaves unexpectedly, print the integer and confirm it matches a declared enumerator. If an enum defined in a header causes multiple-definition errors, check that the header has include guards or #pragma once. If warnings differ between compilers, compile with the strictest warning set you can and fix the underlying issue rather than suppressing it.

Frequently Asked Questions

What is the difference between enum and enum class?

enum class is scoped: enumerators live inside the enum's name and do not convert implicitly to integers. Plain enum puts enumerators in the enclosing scope and converts implicitly. Prefer enum class for new code.

Can an enum have explicit values?

Yes. Write enum class Code { Ok = 200, Error = 500 };. Values must be integral constant expressions, and later enumerators default to the previous value plus one.

How do I convert an enum to a string?

C++ does not generate names automatically. Write a function with a switch that returns a string literal for each enumerator, and keep it next to the enum so it is updated together.

Can I use an enum as an array index?

With an unscoped enum, yes, because it converts to an integer. With a scoped enum, cast first: arr[static_cast<size_t>(Color::Red)]. Make sure the enum values start at 0 and are contiguous if you index directly.

What underlying type should I choose?

Use the default int unless you need a specific size for storage, serialization, or interop with a C API. If you fix the type, document it because it affects binary layout.

Can two enumerators have the same value?

Yes. Aliases are allowed, for example enum class E { A = 1, B = 1 };. Comparisons and switches treat them as the same value, so use aliases only when that behavior is intended.