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.
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:
Numeric value of today: 4