When you first start programming, you will often need to show a set of fixed values. Think about making a game and needing to keep track of the four main directions: North, South, East, and West. You might use numbers like 0, 1, 2, and 3, but after writing hundreds of lines of code, it gets hard to remember which number means “north”. Enumeration in C++ is the answer. Enums let you give names to those strange numbers that make sense.
Enumeration in C++ Definition
It is a custom data type made up of a group of named integer constants. To make these types, you use the word “enum.” You are making a new type that can only carry certain values when you define an enum.
The compiler gives these names integer values starting at 0 by default. For instance, in a list of colours, the first colour gets 0, the second gets 1, and so on. This keeps the logic connected to integers while letting the programmer work with words.
How to Declare an Enumeration in C++?
You use the enum keyword and the name of the enumeration to make an enum. You put the constants inside curly brackets and separate them with commas.
Syntax Structure:
C++
enum EnumName {
Value1,
Value2,
Value3
};
You can make variables of this new type once you have declared it. This is very helpful in switch statements and conditional logic when you want to make sure that only valid predefined values are used.
Enumeration in C++ Example
Let’s look at a real-world enum in C++ example. Let’s say we want to show how hard a software program is.
C++
#include <iostream>
using namespace std;
// Defining the enumeration
enum Difficulty {
Easy, // Defaults to 0
Medium, // Defaults to 1
Hard // Defaults to 2
};
int main() {
// Creating an enum variable
Difficulty myLevel = Medium;
if (myLevel == Medium) {
cout << “The difficulty is set to Medium with value: “ << myLevel;
}
return 0;
}
The word “medium” is considerably easier to understand than the number 1 in this case. You can easily add a “Very Hard” level later by just updating the enum list instead of having to look through all of your code for specific integers.
Changing Values in Enumeration in C++
The compiler starts counting at 0, but you don’t have to stick with that. You can give any or all of the elements particular values with C++ enumeration.
- Partial Assignment: If you set the first value to 10, the subsequent values will be 11, 12, etc.
- Total Assignment: You can give every single item a unique, non-sequential value.
- Duplicate Values: It’s interesting that two separate names in an enum can have the same integer value, although this isn’t something that happens very often in practice.
Example with Custom Values:
C++
enum StatusCode {
Success = 200,
NotFound = 404,
ServerError = 500
};
Using StatusCode here makes it very clear to anyone reading the code what the numbers mean.
Also Read:
- About C Program: Features, Data Types
- CPP Type – C++ Data Types: For Beginners
- What Are The Basic Programming Fundamentals For Software Development?
- C Syllabus Foundation, Important Topics, Course- PW Skills
- Learn C Programming Language Tutorial
Why Use Enumeration in C++?
Using a C++ enum isn’t only for looks; it also has functional benefits that make your product better.
- Readability: It changes “magic numbers” into names that make sense.
- Maintainability: If you change a value in the enum definition, it changes everywhere in the program.
- Type Safety: It limits the values a variable can have, which lowers the chance of making mistakes in logic.
- Efficiency: The compiler treats enums like integers; thus, they don’t use more memory than regular int variables.
C++ Enumeration vs Macros vs Constants
Before enums were common, programmers used #define macros or const int variables. C++ enumeration, on the other hand, is a more organised way to do things.
| Feature | C++ Enum | Const Variables | Macros (#define) |
| Scope | Follows block scope rules | Follows block scope rules | Global (No scope) |
| Type Safety | High (User-defined type) | Moderate | None (Text replacement) |
| Debugging | Easy (Names show in debugger) | Easy | Difficult |
| Grouping | Groups related constants | Independent | Independent |
Scoped Enumeration in C++ Enum Class
C++11 added a newer version called “Enum Classes” or scoped enums. You can’t have two separate enums with the identical member names in a regular enum. The compiler will give an error if both enum Colour {Red} and enum Traffic {Red} are in the same scope.
This is what scoped enums do:
C++
enum class Color { Red, Green, Blue };
enum class TrafficLight { Red, Yellow, Green };
// Usage
Color myColor = Color::Red;
Using the scope resolution operator (::) keeps names from colliding, which makes your code even stronger.
Enum to String Conversion in C++
One limitation of C++ enumeration is that it does not directly allow you to print the name of the enum value. By default, it prints the integer value.
To convert enum values into readable text, you can use a switch-case or an array mapping.
Using switch-case:
enum Difficulty { Easy, Medium, Hard };
string getDifficulty(Difficulty level) {
switch(level) {
case Easy: return “Easy”;
case Medium: return “Medium”;
case Hard: return “Hard”;
default: return “Unknown”;
}
}
This approach ensures your output is user-friendly and readable.
Anonymous C++ Enumeration
In some cases, you may not need to give a name to your enum. This is where anonymous enums are useful.
enum { North, South, East, West };
Here, the constants exist without being tied to a specific enum type.
These are useful when:
- You only need constants temporarily
- You don’t need to create variables of that enum type
Key Rules of C++ Enumeration
- Enums are not strings: You cannot directly print the name “Easy” using cout << myLevel. It will print the integer value. To print the name, you usually use a switch case or an array of strings.
- Implicit Conversion: Traditional enums can be implicitly converted to integers, but scoped enums (enum class) cannot be converted without an explicit cast.
- Memory: The size of an enum is usually the same as an int, though compilers can sometimes optimise this based on the range of values.
Enumeration in C++ in Switch Case
One of the most powerful ways to use C++ enumeration is within a switch statement. It ensures that you handle every possible state of a variable.
C++
enum WindowState { Opened, Closed, Minimised, Maximised };
void checkState(WindowState state) {
switch (state) {
case Opened:
cout << “Window is wide open.”;
break;
case Closed:
cout << “Window is shut.”;
break;
case Minimised:
cout << “Window is in the taskbar.”;
break;
case Maximised:
cout << “Window covers the screen.”;
break;
}
}
This pattern is a staple in Data Structures and Algorithms (DSA) when managing different states of a process or a node.
C++ Enumeration Benefits
To wrap up the technical details, let’s look at how C++ enumeration transforms code:
- Logical Grouping: It tells the reader that these specific constants belong together.
- Compile-time Checking: The compiler helps ensure you aren’t assigning an invalid integer to an enum type.
- Self-Documenting Code: You don’t need many comments to explain what a variable does if its type is DaysOfWeek and its value is Monday.
This concept might seem simple, but it is a cornerstone of writing professional, scalable C++ applications. Whether you are defining states for a game, error codes for a server, or categories for a database, the C++ enum is your best friend for keeping complexity at bay.
FAQs
What is the basic enumeration definition in C++?
It is a user-defined data type used to assign names to integral constants, improving code readability by replacing numbers with meaningful words.
Can I assign my own values to an enum in C++?
Yes, while the default starts at 0, you can assign specific integer values to any member. For example, in an example, you could set enum Rank {Gold = 10, Silver = 5, Bronze = 1};.
What is the difference between enum and enum class?
A typical C++ enum sends its enumerators to the surrounding scope, which might lead to name conflicts. To avoid these kinds of problems, an enum class (sometimes called a scoped enum) needs to use the class name (for example, Color::Red).
Why is C++ enumeration used in switch statements?
Using a C++ enum in switch statements makes the code easier to read and understand. It lets the compiler make sure that all potential cases of the enumeration are handled, which cuts down on logic problems.
Can a C++ enum hold non-integer values like strings?
No, it only has to do with whole number constants. You have to use an array or a mapping function to do this by hand if you need to map these names to strings.
