cpp / beginner
Snippet
Enumerations for Named Constants
An enum class creates a type-safe way to define a set of named integer constants. Unlike plain enums, enum class prevents implicit conversion to int and requires the Scope resolution operator (::) to access values. This makes code more readable and prevents errors from comparing unrelated enum values.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>enum class DayOfWeek {Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday};int main() {DayOfWeek today = DayOfWeek::Friday;if (today == DayOfWeek::Friday) {std::cout << "It's Friday! Weekend is near." << std::endl;}return 0;}
Breakdown
1
enum class DayOfWeek {
Declares a strongly-typed enumeration called DayOfWeek
2
Monday,
First enum value, implicitly assigned 0
3
Tuesday,
Second enum value, implicitly assigned 1
4
Wednesday,
Third enum value, implicitly assigned 2
5
Thursday,
Fourth enum value, implicitly assigned 3
6
Friday,
Fifth enum value, implicitly assigned 4
7
Saturday,
Sixth enum value, implicitly assigned 5
8
Sunday
Seventh enum value, implicitly assigned 6
9
};
Closes the enum class definition
10
DayOfWeek today = DayOfWeek::Friday;
Creates variable of enum type and assigns Friday value using scope operator
11
if (today == DayOfWeek::Friday) {
Compares today with Friday using scope operator
12
std::cout << "It's Friday! Weekend is near." << std::endl;
Prints message when condition is true
13
}
Closes the if statement