An enum (short for enumeration) is a user-defined data type in C++ that allows you to define a set of named integer constants. Enums improve code readability by giving more meaningful names to numeric values, making the code easier to understand and maintain.
An enumeration is a type that can hold a set of integer values specified by the user. Some of an enumeration’s possible values are named and called enumerators.For example: enum class Color { red, green, blue };
Notes:
Enums are used to represent a collection of related constants.
The constants in an enum are implicitly assigned integer values starting from 0, unless you specify otherwise.
Syntax:
enum EnumName {
EnumValue1,
EnumValue2,
EnumValue3,
// ... more values
};
Example: an enum to represent the days of the week.
#include <iostream>
using namespace std;
// Define an enum for days of the week
enum Day {
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
};
int main() {
// Declare a variable of enum type
Day today = Tuesday; // Assign the value "Tuesday" to today
// Using a switch statement with enum values
switch (today) {
case Sunday:
cout << "Today is Sunday!" << endl;
break;
case Monday:
cout << "Today is Monday!" << endl;
break;
case Tuesday:
cout << "Today is Tuesday!" << endl;
break;
default:
cout << "It's another day!" << endl;
}
return 0;
}
Example: Enum with Custom Values
You can also assign specific integer values to the enum constants.
#include
using namespace std;
// Define an enum with custom values
enum Day {
Sunday = 1, // 1
Monday = 2, // 2
Tuesday = 3, // 3
Wednesday = 4,// 4
Thursday = 5, // 5
Friday = 6, // 6
Saturday = 7 // 7
};
int main() {
// Declare a variable of enum type
Day today = Wednesday; // Assign the value "Wednesday" to today
cout << "Numeric value of today: " << today << endl; // Outputs: 4
return 0;
}
Output:
C++ Enums – Interview Questions
Q 1: What is an enum?
Q 2: Why use enums?
Q 3: Are enum values integers?
Q 4: Can enum values be changed?
Q 5: Example of enum?
C++ Enums – Objective Questions (MCQs)
Q1. What is an enum in C++?
Q2. Which of the following is the correct syntax to declare an enum in C++?
Q3. What is the default value assigned to the first name in an enum if not specified?
Q4. Consider the following code:
enum week {Mon, Tue, Wed, Thu, Fri, Sat, Sun};
cout << Wed;
Q5. Which of the following statements about enums is TRUE?