capypad
0 day streak
cpp / beginner
Snippet

Enumerations for Named Constants

An enumeration (enum class) creates a user-defined type with a set of named integer constants. It improves code readability by replacing magic numbers with meaningful names. The enum class keyword also provides type safety, preventing implicit conversions to int. Each enum value is assigned an integer value starting from 0 by default.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
enum class Color {
Red,
Green,
Blue
};
 
int main() {
Color favorite = Color::Blue;
if (favorite == Color::Blue) {
std::cout << "Blue is selected!" << std::endl;
}
return 0;
}
Breakdown
1
enum class Color {
Defines a strongly-typed enumeration named Color
2
Red, Green, Blue
Three named constants added to the enumeration
3
Color favorite = Color::Blue;
Creates variable of type Color and assigns Blue value
4
Color::Blue
Scope resolution operator accesses enum value