Sitemap
CodeAddict

CodeAddict

Research Professor, Ph.D. | 15+ yrs engineering across 8 fields. I bring AI into any of them. bridge-ai-studio.netlify.app

cpp_030: C++ Enumerations

4 min readMay 13, 2025

--

In this post, we’ll explore enumerations (enum) in C++, a powerful feature for defining a set of named constants. Enums are perfect for representing fixed sets of values, like days of the week, states in a game, or error codes. We’ll cover unscoped enums, scoped enums (enum class), their syntax, and practical uses with examples. At the end, we’ll solve a problem using enums to manage a traffic light system.

Understanding C++ Enumerations

Enumerations allow you to define a custom type with a fixed set of named values, called enumerators. They improve code readability and maintainability by replacing magic numbers or constants with meaningful names. C++ supports two types of enums:

  • Unscoped enums (enum): Traditional enums, less strict, share the namespace with their enclosing scope.
  • Scoped enums (enum class or enum struct): Introduced in C++11, type-safe, and encapsulated within their own scope.

1. Unscoped Enums

Unscoped enums are defined using the enum keyword. Each enumerator is assigned an integer value, starting from 0 by default, incrementing by 1.

Example1

#include <iostream>
using namespace std;

enum Color { RED, GREEN, BLUE }; // Enumerators: RED=0, GREEN=1, BLUE=2

int main() {
Color c = GREEN;
cout << "Color value: " << c << endl; //Color value: 1
return 0;
}

Explanation

  • RED, GREEN, BLUE are enumerators, implicitly assigned values 0, 1, 2.
  • The enum type Color can be used as a variable type.
  • Printing c outputs the underlying integer (1 for GREEN).
  • Key Point: Unscoped enums are implicitly convertible to integers, which can lead to unintended comparisons or errors.

Example2: Day of the Week

Assign specific values to represent days.

#include <iostream>
using namespace std;

enum Day { MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

int main() {
Day today = WEDNESDAY;
cout << "Today is day number: " << today << endl;
return 0;
}

Output:

Today is day number: 3

Explanation: MONDAY is explicitly set to 1, so TUESDAY is 2, WEDNESDAY is 3, etc. Explicit values help when specific numbers are needed.

2. Scoped Enums

Scoped enums, defined with enum class or enum struct, are type-safe and don’t pollute the enclosing namespace. They require explicit scoping (e.g., EnumName::Value).

Example1

#include <iostream>
using namespace std;

enum class Fruit { APPLE, BANANA, ORANGE };

int main() {
Fruit f = Fruit::BANANA;
// cout << f; // Error: No implicit conversion to int
if (f == Fruit::BANANA) {
cout << "Selected fruit is BANANA" << endl;
}
return 0;
}

Get CodeAddict’s stories in your inbox

Join Medium for free to get updates from this writer.

Explanation

  • Fruit::APPLE, Fruit::BANANA, etc., are accessed using the scope operator (::).
  • No implicit conversion to int, preventing accidental misuse.
  • Key Point: Use scoped enums for better type safety and to avoid name conflicts.

Example: Game States

Manage states in a game with a scoped enum.

#include <iostream>
using namespace std;

enum class GameState { MENU, PLAYING, PAUSED, GAME_OVER };

int main() {
GameState state = GameState::PLAYING;
if (state == GameState::PLAYING) {
cout << "Game is running" << endl;
} else if (state == GameState::PAUSED) {
cout << "Game is paused" << endl;
}
return 0;
}

Output:

Game is running

3. Specifying Underlying Types

Both unscoped and scoped enums can specify an underlying type (e.g., int, char, unsigned int) to control storage or enforce specific value ranges.

Example

#include <iostream>
using namespace std;

enum class Status : char { OK = 'O', ERROR = 'E', UNKNOWN = 'U' };

int main() {
Status s = Status::OK;
cout << "Status code: " << static_cast<char>(s) << endl; //Status code: O
return 0;
}

Explanation

  • Status uses char as its underlying type, so enumerators are stored as char values.
  • Use static_cast to access the underlying value for printing.
  • Key Point: Useful for memory optimization or interfacing with systems expecting specific types.

4. Practical Problem: Traffic Light System

Let’s use a scoped enum to model a traffic light system that transitions between states and displays appropriate messages.

Example

#include <iostream>
using namespace std;

enum class TrafficLight { RED, YELLOW, GREEN };

void displayLight(TrafficLight light) {
switch (light) {
case TrafficLight::RED:
cout << "Stop!" << endl;
break;
case TrafficLight::YELLOW:
cout << "Prepare to stop." << endl;
break;
case TrafficLight::GREEN:
cout << "Go!" << endl;
break;
}
}

int main() {
TrafficLight current = TrafficLight::RED;
displayLight(current);

current = TrafficLight::YELLOW;
displayLight(current);

current = TrafficLight::GREEN;
displayLight(current);

return 0;
}

Output:

Stop!
Prepare to stop.
Go!

Explanation

  • TrafficLight is a scoped enum with three states.
  • The displayLight function uses a switch to handle each state.
  • Key Point: Enums make the code self-documenting, as TrafficLight::RED is more descriptive than a raw integer.

5. Solving the Traffic Light System Without Enums

Instead of using enums, we can represent traffic light states with std::string variables. This approach uses string literals (“RED”, “YELLOW”, “GREEN”) to track the state and compares them to display messages.

#include <iostream>
#include <string>
using namespace std;

void displayLight(const string& light) {
if (light == "RED") {
cout << "Stop!" << endl;
} else if (light == "YELLOW") {
cout << "Prepare to stop." << endl;
} else if (light == "GREEN") {
cout << "Go!" << endl;
} else {
cout << "Invalid light state!" << endl;
}
}

int main() {
string current = "RED";
displayLight(current);

current = "YELLOW";
displayLight(current);

current = "GREEN";
displayLight(current);

current = "BLUE"; // Invalid state
displayLight(current);

return 0;
}

--

--

CodeAddict
CodeAddict

Written by CodeAddict

Research Professor, Ph.D. | 15+ yrs engineering across 8 fields. I bring AI into any of them. bridge-ai-studio.netlify.app