Enums
Overview
If a video game character can be in 3 states: Menu, Playing, or Dead. You could use integers (0 = Menu, 1 = Playing, 2 = Dead), but writing if (state == 2) makes the code totally unreadable and highly prone to bugs.
An Enum (Enumeration) is a custom data type that allows you to assign human-readable English names to underlying integers. By default, the compiler assigns the first item to 0, the second to 1, and so on. Modern C++ heavily relies on enum class (Scoped Enums) because they enforce strict type safety, ensuring you can't accidentally add a Menu state to a Dead state.
Syntax
// --- 1. OLD C-STYLE ENUM (Unsafe, avoid) ---
enum Difficulty { EASY, NORMAL, HARD };
// Behind the scenes: EASY = 0, NORMAL = 1, HARD = 2
// --- 2. MODERN SCOPED ENUM CLASS (Safe) ---
enum class GameState {
MENU,
PLAYING,
GAMEOVER
};
int main() {
// Requires the scope resolution operator (::)
GameState current = GameState::PLAYING;
if (current == GameState::GAMEOVER) {
// Handle death
}
return 0;
}Common Pitfalls
- Using standard
enuminstead ofenum class. Standard enums 'leak' their variable names into the global scope. If you haveenum TrafficLight { RED }andenum AlertLevel { RED }, the compiler crashes because 'RED' is defined twice.enum classsolves this natively. - Trying to print an Enum directly to the terminal.
cout << GameState::MENUcauses a massive compiler error forenum class. Enums are strict mathematical constructs, not strings. You must cast it to an integer or use aswitchto print strings.
Interview Questions
enum class over the legacy C-style enum?enum class provides two critical features: Scope and Strong Typing. The values are safely trapped inside their scope (preventing naming collisions like 'RED'), and they will not implicitly convert to integers. This prevents catastrophic logic bugs, like accidentally passing a 'TrafficLight::GREEN' into a function expecting a 'FileStatus::SUCCESS'.
Real-World Example
Using enum class with a switch statement for blazing fast, highly readable State Machines.
#include <iostream>
enum class Weapon { SWORD, BOW, MAGIC };
int main() {
Weapon equipped = Weapon::BOW;
// The compiler optimizes this into a high-speed Jump Table
switch (equipped) {
case Weapon::SWORD:
std::cout << "Swing sword!\n";
break;
case Weapon::BOW:
std::cout << "Fire arrow!\n";
break;
case Weapon::MAGIC:
std::cout << "Cast spell!\n";
break;
}
return 0;
}Check Your Knowledge
Test your understanding of Enums with these quick questions.