Enumerations in C++
Introduction
Enumerations (enums) are a user-defined data type in C++ that consist of integral constants. To define an enumeration, the enum
keyword is used. Enums are used to assign names to the integral constants which make a program easy to read and maintain.
Defining an Enumeration
To define an enumeration, you use the enum
keyword followed by the name of the enumeration and the list of constants enclosed in curly braces.
enum Color {RED, GREEN, BLUE};
In this example, Color
is an enumeration with three constants: RED
, GREEN
, and BLUE
. By default, the value of RED
is 0
, GREEN
is 1
, and BLUE
is 2
.
Using Enumerations
You can declare variables of the type of an enumeration and assign one of the enum constants to them.
Color myColor; myColor = RED;
Here, myColor
is a variable of type Color
and is assigned the value RED
.
Enumerations with Specific Values
You can also assign specific values to the constants in an enumeration.
enum Fruit {APPLE = 2, ORANGE = 4, BANANA = 6};
In this example, APPLE
has the value 2
, ORANGE
has the value 4
, and BANANA
has the value 6
.
Enumeration Scope
By default, enumerations have global scope. However, you can use the enum class
(or enum struct
) keyword to define scoped enumerations which help avoid name conflicts.
enum class Color {RED, GREEN, BLUE}; enum class Fruit {APPLE, ORANGE, BANANA};
In this example, Color
and Fruit
are scoped enumerations. To use the constants, you need to specify the enumeration name.
Color myColor = Color::RED; Fruit myFruit = Fruit::APPLE;
Advantages of Enumerations
Enumerations provide several advantages:
- Improved code readability
- Better error checking
- Namespace management with scoped enums
Example Program
Here is a complete example program that demonstrates the usage of enumerations in C++:
#include <iostream> using namespace std; enum class Color {RED, GREEN, BLUE}; enum class Fruit {APPLE, ORANGE, BANANA}; int main() { Color myColor = Color::GREEN; Fruit myFruit = Fruit::BANANA; if (myColor == Color::GREEN) { cout << "The color is green." << endl; } if (myFruit == Fruit::BANANA) { cout << "The fruit is banana." << endl; } return 0; }
In this program, we define two scoped enumerations: Color
and Fruit
. We then use these enums to set the values and compare them in if
statements.