C++ Enums - A Simple Introduction
Enumerations, commonly known as enums, are a simple but powerful data type in C++. They allow you to define a set of named integral constants, making your code more readable and maintainable. In this guide, we'll introduce you to the concept of enums and show you how to use them with sample code.
Defining Enums
In C++, you can define an enum using the `enum` keyword, followed by a set of constant names enclosed in curly braces. Here's an example of defining a simple enum for days of the week:
#include <iostream>
using namespace std;
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
int main() {
Day today = Wednesday;
cout << "Today is " << today << endl;
return 0;
}
In this example, we define an enum `Day` with constant values for the days of the week. We then create a variable `today` and set it to `Wednesday`. When we print the value of `today`, it will be displayed as an integer corresponding to the position of `Wednesday` in the enum (which is 3, as enums start from 0 by default).
Custom Values for Enum Constants
You can assign custom integral values to enum constants. Here's an example:
#include <iostream>
using namespace std;
enum Month { January = 1, February, March, April, May, June, July, August, September, October, November, December };
int main() {
Month currentMonth = July;
cout << "The current month is " << currentMonth << endl;
return 0;
}
In this example, we assign custom values to the `Month` enum constants, starting from 1 for `January`. When we set `currentMonth` to `July` and print it, it will display the corresponding value (7 in this case).
Enums for Improved Code Readability
Enums are often used to improve the readability of code by giving meaningful names to integral constants. Instead of using magic numbers, you can use enums to make your code more self-explanatory. For example:
#include <iostream>
using namespace std;
enum class Color { Red, Green, Blue };
int main() {
Color selectedColor = Color::Green;
if (selectedColor == Color::Red) {
cout << "You chose the red color." << endl;
} else if (selectedColor == Color::Green) {
cout << "You chose the green color." << endl;
} else if (selectedColor == Color::Blue) {
cout << "You chose the blue color." << endl;
} else {
cout << "Unknown color." << endl;
}
return 0;
}
In this example, we define a scoped enum `Color` and use it to represent colors. This makes the code more readable and less error-prone when comparing colors.
Conclusion
Enums in C++ are a straightforward yet valuable feature for defining named integral constants. They improve code readability and maintainability, reducing the reliance on magic numbers. As you continue your C++ journey, you'll find enums useful for representing various types of data.