Enums
C++ Enums (Enumerations)
Definition: An enumeration (or enum) is a user-defined data type that consists of a set of named integer constants. Enums are used to give clear, readable names to numerical values, making source code significantly easier to understand, maintain, and debug.
Why: Standard beginner tracks introduce enums alongside structures as a key custom data type. Instead of using raw, unhelpful magic numbers (like 0, 1, or 2) to represent status flags or configurations in your loops and conditional statements, enums allow you to use self-explanatory words.
Declaration and Assignment Syntax
To create an enum, use the enum keyword followed by a custom name. Inside the curly braces, list the words that represent your constants. Like structures, an enum definition must terminate with a semicolon (;).
enum EnumName {
CONSTANT1,
CONSTANT2,
CONSTANT3
};
Example: Setting a Difficulty Level
In this example, the program defines an enum named Level. When we print an enum value, the compiler outputs its underlying numerical integer index:
#include <iostream> using namespace std; // Defining the enumeration enum Level { LOW, // Implicitly maps to 0 MEDIUM, // Implicitly maps to 1 HIGH // Implicitly maps to 2 }; int main() { // Creating an enum variable and assigning a value Level myLevel = MEDIUM; // Printing the variable displays its integer counterpart cout << "Selected Level Value: " << myLevel << endl; // Outputs: 1 return 0; }
Implicit vs. Explicit Value Mapping
| Mapping Type | Code Example | Behavior |
|---|---|---|
| Implicit (Default) | enum Status { PENDING, ACTIVE }; |
The values are assigned automatically starting at 0 and incrementing by 1 (PENDING = 0, ACTIVE = 1). |
| Explicit Custom | enum Code { OK = 200, ERROR = 404 }; |
You override the values with explicit integers. This is extremely useful for network codes or database states. |
Key Notes
- Underlying Values: By default, the first item in an enum has the value 0, the second has 1, and so on. If you explicitly set the first value to something else (e.g.,
LOW = 5), the subsequent unassigned values will count up from there sequentially (MEDIUM will automatically become 6, HIGH will become 7). - Readability over Console Text: A common misconception is that printing an enum variable will print its word label (like "MEDIUM"). It doesn't—it outputs the integer index value. Enums exist purely to help the *programmer* write cleaner source code.
- Switch Statement Synergy: Enums work perfectly with
switchstatements. Since enums resolve down to integers, they create elegant, self-documenting control systems:switch(myLevel) { case LOW: ... case MEDIUM: ... }. - Modern C++ Upgrade (enum class): In modern C++ (C++11 and beyond), it is highly recommended to use scoped enums by adding the
classkeyword (e.g.,enum class Level { LOW, HIGH };). This prevents name conflicts if two different enums happen to use the same word constant.