Enums in C++
0 116
In C++, enums (short for enumerations) are user-defined data types that consist of integral constants. They are a great way to assign names to a set of numeric values, making your code more readable and easier to maintain.
What is an Enum?
An enum
allows you to define a type that can hold a set of predefined constants. These constants are represented by names and internally assigned integer values starting from 0 by default.
Syntax of Enum in C++
enum Level {
LOW,
MEDIUM,
HIGH
};
In this example, LOW
is 0, MEDIUM
is 1, and HIGH
is 2. These values are assigned automatically unless specified otherwise.
Using Enums in Code
You can use enum values to declare variables and perform comparisons:
#include <iostream>
using namespace std;
enum Level {
LOW,
MEDIUM,
HIGH
};
int main() {
Level myLevel = MEDIUM;
if (myLevel == MEDIUM) {
cout << "Medium level selected.";
}
return 0;
}
This program checks if the current level is MEDIUM
and prints a message accordingly.
Custom Enum Values
You can also assign specific integer values to enum members:
enum Day {
MON = 1,
TUE = 2,
WED = 3,
THU = 4,
FRI = 5
};
Now, each day has a corresponding value as defined.
Enum Classes (Scoped Enums)
In modern C++, you can use enum class for better type safety and scoping:
enum class Direction {
North,
South,
East,
West
};
With enum class
, you must use the scope resolution operator to access members:
Direction d = Direction::North;
This prevents name conflicts and ensures that enum values belong strictly to their type.
Benefits of Using Enums
- Improves code readability by using descriptive names instead of numbers
- Makes it easier to manage sets of related constants
- Reduces the chances of errors caused by hard-coded values
enum class
provides better type safety
Conclusion
Enums in C++ are a powerful way to manage constant values with meaningful names. Whether you're working with classic enums or scoped enum classes, they help make your code cleaner, safer, and easier to understand.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments