Enumerations

Enumerations in C++ are user-defined data types used to assign names to integral constants. They make programs more readable and easier to manage.

What is an Enumeration?

An enumeration (enum) is a data type that consists of a set of named integer constants.

Instead of using numbers directly, you can use meaningful names.

Why Use Enumerations?

Enumerations are useful because they:

  • Improve code readability
  • Make programs easier to understand
  • Reduce use of magic numbers
  • Help organize related constants

Syntax of Enumeration

enum EnumName {
constant1,
constant2,
constant3
};

Example of Enumeration

#include <iostream>
using namespace std;

enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday
};

int main() {

Day today = Wednesday;

cout << today;

return 0;
}

Output

2

How Enumerations Work

By default:

  • First value starts from 0
  • Next values increase automatically

Example:

Monday = 0
Tuesday = 1
Wednesday = 2

Assigning Custom Values

You can assign your own values.

enum Status {
Success = 1,
Error = 2,
Pending = 3
};

Example with Custom Values

#include <iostream>
using namespace std;

enum Level {
Low = 10,
Medium = 20,
High = 30
};

int main() {

Level l = High;

cout << l;

return 0;
}

Output

30

Using Enumeration in Conditions

#include <iostream>
using namespace std;

enum TrafficLight {
Red,
Yellow,
Green
};

int main() {

TrafficLight signal = Green;

if (signal == Green) {
cout << "Go";
}

return 0;
}

Enumeration with switch Statement

switch(signal) {

case Red:
cout << "Stop";
break;

case Green:
cout << "Go";
break;
}

Enum Class (Modern C++)

Modern C++ provides strongly typed enumerations.

enum class Color {
Red,
Green,
Blue
};

Accessing values:

Color::Red

Difference Between enum and enum class

enumenum class
Less type safetyStrong type safety
Values accessible directlyAccess using scope operator
Older styleModern C++ style

Advantages of Enumerations

  • Makes code readable
  • Simplifies constant management
  • Improves program clarity
  • Reduces errors from numeric values

Real-Life Example

Think of traffic signals:

  • Red
  • Yellow
  • Green

Using names is much easier than remembering numbers like 0, 1, or 2.

Why Enumerations are Important

Enumerations are important because they:

  • Improve program organization
  • Help manage fixed values
  • Make code self-explanatory
  • Support better programming practices

Conclusion

Enumerations in C++ are useful user-defined data types that assign names to integer constants. They improve readability, reduce confusion, and help create clean and maintainable programs.

Home » Intermediate C++ > Structures and Enums > Enumerations