An Enumeration (enum) in C++ is a user-defined data type that assigns meaningful names to a set of integer constants.
1️⃣ Direction Example in C++
📌 Using enum
to define directions.
#include <iostream>
using namespace std;
enum Direction { NORTH, SOUTH, EAST, WEST };
void showDirection(Direction d) {
switch (d) {
case NORTH: cout << "You are moving NORTH." << endl; break;
case SOUTH: cout << "You are moving SOUTH." << endl; break;
case EAST: cout << "You are moving EAST." << endl; break;
case WEST: cout << "You are moving WEST." << endl; break;
default: cout << "Invalid direction." << endl;
}
}
int main() {
Direction dir;
int choice;
cout << "Enter direction (0-NORTH, 1-SOUTH, 2-EAST, 3-WEST): ";
cin >> choice;
if (choice >= 0 && choice <= 3) {
dir = static_cast<Direction>(choice);
showDirection(dir);
} else {
cout << "Invalid input!" << endl;
}
return 0;
}
🔹 Output
Enter direction (0-NORTH, 1-SOUTH, 2-EAST, 3-WEST): 2
You are moving EAST.
📌 Key Points:
✔ enum Direction
creates meaningful constants (NORTH = 0
, SOUTH = 1
, etc.).
✔ switch
statement is used to print the selected direction.
✔ static_cast<Direction>(choice)
converts integer input to an enum type.
2️⃣ Week Days Example in C++
📌 Using enum
to represent days of the week.
#include <iostream>
using namespace std;
enum WeekDays { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
void showDay(WeekDays day) {
switch (day) {
case SUNDAY: cout << "It's Sunday, time to relax!" << endl; break;
case MONDAY: cout << "It's Monday, back to work!" << endl; break;
case TUESDAY: cout << "It's Tuesday, keep going!" << endl; break;
case WEDNESDAY: cout << "It's Wednesday, halfway there!" << endl; break;
case THURSDAY: cout << "It's Thursday, almost the weekend!" << endl; break;
case FRIDAY: cout << "It's Friday, weekend is near!" << endl; break;
case SATURDAY: cout << "It's Saturday, enjoy your day!" << endl; break;
default: cout << "Invalid day!" << endl;
}
}
int main() {
WeekDays today;
int choice;
cout << "Enter day (0-SUNDAY, 1-MONDAY, ..., 6-SATURDAY): ";
cin >> choice;
if (choice >= 0 && choice <= 6) {
today = static_cast<WeekDays>(choice);
showDay(today);
} else {
cout << "Invalid input!" << endl;
}
return 0;
}
🔹 Output
Enter day (0-SUNDAY, 1-MONDAY, ..., 6-SATURDAY): 5
It's Friday, weekend is near!
📌 Key Points:
✔ enum WeekDays
represents each day with a unique integer value (SUNDAY = 0
, MONDAY = 1
, etc.).
✔ The user selects a day by entering a number from 0 to 6.
✔ The program prints a custom message based on the selected day.
📌 Summary
✔ Enums improve readability by replacing integer values with meaningful names.
✔ They are strongly typed, preventing accidental invalid assignments.
✔ Enums can be used in switch statements for clear, structured logic.
🚀 Want more examples? Let me know! 🔥
0 Comments