In C++, Enumeration (Enum) serves as a custom data type with a defined collection of named integer constants. Enumerations are created using the enum keyword, enhancing code readability and maintainability.
It is applicable for various purposes like days (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday), months (January, February, March, April, May, June, July, August, September, October, November, December), cardinal directions (NORTH, SOUTH, EAST, and WEST), and more. The C++ enum constants are inherently static and final.
Syntax
It has the following syntax:
enum enum_name {
val1, va2, val3, ...
};
In this syntax,
- enum: It is used to declare the enumeration type.
- enum_name: It represents the enumeration name.
- val1, val2, val3…: It represents the integral constants.
C++ Enumeration Example
Let's consider an example to demonstrate the Enumeration feature in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
enum month {Jan, Feb, Mar, Apr, May, June};
int main() //Main Function
{
month mon_name;
mon_name = Mar;
cout << "Month: " << mon_name+1<<endl;
return 0;
}
Output:
Month: 3
Explanation
In this instance, we define an enum called month that includes monname. Subsequently, the monname variable is set to the value Mar. When monname + 1 is outputted, it shows 3 due to enum values starting from 0 by default. Therefore, Mar is equivalent to 2, and 2 + 1 equals 3. The result of monname + 1 is 3, representing March.
Initializing Enum
In C++, initialization of an enum type variable is mandatory by assigning a value to a variable of the enum type. The enum variable can be initialized using the assignment (=) operator, which is then followed by an enum constant.
C++ Initializing Enum Example
Let's consider a scenario to demonstrate the process of initializing an enumeration in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
enum Color {
RED,
GREEN,
BLUE
};
int main() { //Main Function
Color myColor = BLUE;
cout << "My colour value: " << myColor << endl;
return 0;
}
Output:
My colour value: 2
Explanation
In this illustration, we define an enum named Color containing the elements RED, GREEN, and BLUE. Each element is implicitly assigned the integer values 0, 1, and 2 respectively. Within the main function, a variable named myColor is declared and set to BLUE. Subsequently, the integer value representing myColor (2) is output to the console.
Changing Values of Named Constant
In C++, the enum keyword is utilized to create a custom data type comprising named integral constants. To adjust the values associated with these named constants, manual assignment of values to enum members is necessary.
Syntax
It has the following syntax:
enum enum_name {
name1 = value1,
name2 = value2,
name3, // will be value2 + 1
...
};
In this syntax,
- enum_name: It represents the enumeration name.
- name1, name2, name3: It represents the named constants.
- If a value is not explicitly assigned, it increments from the previous value.
C++ Changing Values of Named Constant
Let's consider an example to demonstrate how to modify the values of named constants in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
enum Priority {
LOW = 10,
MEDIUM = 20,
HIGH = 30,
URGENT = 40
};
int main() { //Main Function
Priority taskPriority = HIGH;
cout << "Priority level: " << taskPriority << endl;
return 0;
}
Output:
Priority level: 30
Explanation
In this instance, the Priority enum's named constants are specifically assigned values of 10, 20, 30, and 40. These values remain constant throughout the program's execution, as they are defined as final, distinct from the default 0-based enum values.
Types of Enumeration
Enumeration can be primarily classified into two groups: Scoped Enumeration and Unscoped Enumeration.
Now, we will examine each of these enumerations individually.
1) Unscoped Enumeration
In C++, the unscoped enum serves as the fundamental form of enumeration. The unscoped enumeration is created by using the enum keyword with enumerator names specified within the encompassing scope.
Unscoped enumeration defaults to assigning integer values from 0 onwards unless specified otherwise. Enumerator names can be easily converted to integers, allowing smooth interaction with arithmetic and relational operators. However, assigning the enumerator name to another variable within the same scope may lead to errors.
C++ Unscoped Enumeration Example
Let's consider a scenario to demonstrate the unscoped enumeration feature in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
int main() { //Main Function
Day today = Wed;
cout << "Numeric value of today: " << today << endl;
if (today == Wed) {
cout << "It is a mid-day of the Week" << endl;
}
return 0;
}
Output:
Numeric value of today: 3
It is a mid-day of the Week
Explanation
In this instance, a non-scoped enumeration named Day is utilized to denote the days of the week, initializing with implicit integer values beginning at 0. Subsequently, it assigns Wednesday to the variable "today," outputs its numerical value, and verifies if it corresponds to Wednesday to showcase a specific message.
2) Scoped Enumeration
Enum classes, also known as scoped enums, are created using the enum class keyword in C++ programming. This feature was added in the C++11 standard to enhance type safety and prevent naming clashes. Unlike traditional enums, scoped enums do not automatically convert to integers and require the use of the scope resolution (::) operator to access their values.
C++ Scoped Enumeration Example
Let's consider a scenario to demonstrate the scoped enumeration feature in C++.
Example
#include <iostream>
using namespace std; //Using Standard Namespace
enum class Color { Red, Yellow, White };
int main() { //Main Function
Color c = Color::Yellow; //using scoped enumeration
if (c == Color::Yellow) {
cout << "The color is Yellow" << endl;
}
cout << "Integer value of color: " << static_cast<int>(c) << endl;
return 0;
}
Output:
The color is Yellow
Integer value of color: 1
Explanation
In this instance, we are creating an enum class named Color containing three constant color values. Subsequently, the variable 'c' is set to the scoped enumerator Color::Yellow, followed by a check on its value. Since enum classes do not support automatic conversion to integers, they employ static_cast<int>(c) to display the enum constant's integer representation.
Enum as Function Parameters
In C++, enums can be employed as function arguments. When passing an enum as a function parameter, it is necessary to specify the enum name along with its individual values.
C++ Enum Passing as a Parameter Example
Let's consider an instance to demonstrate the process of passing an enumeration as an argument in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
enum Operation { Add, Subtract };
int calculate(int a, int b, Operation op) {
if (op == Add)
return a + b; //Return addition
else
return a - b; //Return Subtraction
}
int main() { //Main Function
int result = calculate(15, 10, Add);
cout << "Result: " << result << endl; //Prints the result
return 0;
}
Output:
Result: 25
Explanation
In this instance, an Operation enum is selected and passed as an argument to the calculate function to determine whether to use the add or subtract method. Subsequently, the function is invoked with the Add method, resulting in the display of the returned value of 25.
Points to Remember for C++ Enum
- Enum improves the type safety.
- Enum can be easily used in switch cases.
- Enum can be traversed.
- Enum cannot have fields, constructors, and methods.
- Enum may implement many interfaces but cannot extend any class because it internally extends the Enum class.
Advantages of Enums
Several advantages of Enums in C++ are as follows:
- Enums offers better names to values, which makes the code more readable and easier to understand and maintain.
- Enums in C++ limit the assigned values, particularly with scoped enums, which are less error-prone and remove name conflicts.
- Enums aid in code structuring by collecting associated constants that enhance code readability, ensure type safety, make function interfaces cleaner, and allow for more convenient refactoring.
- Enums get along well with switch statements and enable direct control over underlying types with assigned values.
Limitations of Enums
Several limitations of Enums in C++ are as follows:
- Unscoped enums can lead to name clashes and implicit conversion to integers, which will make the code more prone to errors.
- Enums have a finite set of values and the absence of member functions that cannot be extended at runtime.
- Enum values can be shown as integers by debuggers, which makes it more difficult to discern their meaning.
Conclusion
In summary, C++ enum allows us to define a collection of named constants, enhancing the readability and type safety of our code. Enums can be assigned specific values, utilized as function parameters, and strengthened with scoped enums (enum class) to bolster type safety. While offering advantages like improved code organization and readability, they may also pose challenges such as potential naming conflicts and limited functionality in certain scenarios.
C++ Enumeration MCQs
The initial value of the first enum constant is
- Undefined.
2) Which of the following operations is true about enum class in C++?
- It allows implicit type conversion to integers.
- It can cause name clashes with other enums.
- It enforces type safety and prevents name clashes.
- It has no scope and allows direct access to values.
Option C) It ensures type security and avoids conflicts in naming.
3) What happens when we add 1 to an enum constant in C++?
- It increases the value of the constant by 1.
- It gives an error because enums cannot be altered.
- It changes the type of the constant.
- It results in the next enum value if enumerations are sequential.
Selecting option D will lead to the generation of the subsequent enum value in cases where enumerations are in a sequential order.
4) Which of the following options is not an advantage of using enums in C++?
- Enhanced readability
- Type safety
- Name conflicts with other variables
- Improved functionality with switch statements
5) How can an enum's value be manually set in C++?
- By using the enum class keyword.
- By assigning specific values during declaration.
- By using pointers.
- By initializing the enum inside the main function.
By specifying particular values at the time of defining variables.